Ошибка unexpected end of zlib input stream

There is something wrong with GZIPInputStream or GZIPOutputStream. Just please read the following code (or run it and see what happens):

def main(a: Array[String]) {
    val name = "test.dat"
    new GZIPOutputStream(new FileOutputStream(name)).write(10)
    println(new GZIPInputStream(new FileInputStream(name)).read())
}

It creates a file test.dat, writes a single byte 10 formatting by GZIP, and read the byte in the same file with the same format.

And this is what I got running it:

Exception in thread "main" java.io.EOFException: Unexpected end of ZLIB input stream
    at java.util.zip.InflaterInputStream.fill(Unknown Source)
    at java.util.zip.InflaterInputStream.read(Unknown Source)
    at java.util.zip.GZIPInputStream.read(Unknown Source)
    at java.util.zip.InflaterInputStream.read(Unknown Source)
    at nbt.Test$.main(Test.scala:13)
    at nbt.Test.main(Test.scala)

The reading line seems going the wrong way for some reason.

I googled the error Unexpected end of ZLIB input stream and found some bug reports to Oracle, which were issued around 2007-2010. So I guess the bug still remains in some way, but I’m not sure if my code is right, so let me post this here and listen to your advice. Thank you!

I get a Unexpected end of ZLIB input stream error when I try to read a model, I committed before. I have tried the SingleCheckinAndDownload.java example and the error occurs to. After a commit the 3D-view in bimviews does also not work. There is only the loading project bar but without progress. Is there something wrong with my code or is there a problem with the server?

Error :

[AWT-EventQueue-0] INFO org.bimserver.emf.SharedJsonDeserializer — # Objects: 1772
java.io.EOFException: Unexpected end of ZLIB input stream
at java.util.zip.InflaterInputStream.fill(InflaterInputStream.java:240)
at java.util.zip.InflaterInputStream.read(InflaterInputStream.java:158)
at java.util.zip.GZIPInputStream.read(GZIPInputStream.java:117)
at java.io.FilterInputStream.read(FilterInputStream.java:107)
at org.apache.http.client.entity.LazyDecompressingInputStream.read(LazyDecompressingInputStream.java:67)
at org.apache.commons.io.IOUtils.copyLarge(IOUtils.java:1792)
at org.apache.commons.io.IOUtils.copyLarge(IOUtils.java:1769)
at org.apache.commons.io.IOUtils.copy(IOUtils.java:1744)
at org.bimserver.client.ClientIfcModel.loadGeometry(ClientIfcModel.java:347)
at org.bimserver.client.ClientIfcModel.loadDeep(ClientIfcModel.java:303)
at org.bimserver.client.ClientIfcModel.(ClientIfcModel.java:115)
at org.bimserver.client.BimServerClient.getModel(BimServerClient.java:202)
at at.ac.get.opensourcebimeditor.globalsets.setproject(globalsets.java:316)
at at.ac.get.opensourcebimeditor.globalsets.setproject(globalsets.java:491)
at at.ac.get.opensourcebimeditor.GUI.ProjectGUI.jComboBox1ActionPerformed(ProjectGUI.java:410)
at at.ac.get.opensourcebimeditor.GUI.ProjectGUI.access$000(ProjectGUI.java:30)
at at.ac.get.opensourcebimeditor.GUI.ProjectGUI$1.actionPerformed(ProjectGUI.java:147)
at javax.swing.JComboBox.fireActionEvent(JComboBox.java:1258)
at javax.swing.JComboBox.setSelectedItem(JComboBox.java:586)
at javax.swing.JComboBox.setSelectedIndex(JComboBox.java:622)
at javax.swing.plaf.basic.BasicComboPopup$Handler.mouseReleased(BasicComboPopup.java:861)
at java.awt.AWTEventMulticaster.mouseReleased(AWTEventMulticaster.java:290)
at java.awt.Component.processMouseEvent(Component.java:6533)
at javax.swing.JComponent.processMouseEvent(JComponent.java:3324)
at javax.swing.plaf.basic.BasicComboPopup$1.processMouseEvent(BasicComboPopup.java:510)
at java.awt.Component.processEvent(Component.java:6298)
at java.awt.Container.processEvent(Container.java:2236)
at java.awt.Component.dispatchEventImpl(Component.java:4889)
at java.awt.Container.dispatchEventImpl(Container.java:2294)
at java.awt.Component.dispatchEvent(Component.java:4711)
at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4888)
at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4525)
at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4466)
at java.awt.Container.dispatchEventImpl(Container.java:2280)
at java.awt.Window.dispatchEventImpl(Window.java:2746)
at java.awt.Component.dispatchEvent(Component.java:4711)
at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:758)
at java.awt.EventQueue.access$500(EventQueue.java:97)
at java.awt.EventQueue$3.run(EventQueue.java:709)
at java.awt.EventQueue$3.run(EventQueue.java:703)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:80)
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:90)
at java.awt.EventQueue$4.run(EventQueue.java:731)
at java.awt.EventQueue$4.run(EventQueue.java:729)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:80)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:728)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:201)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:116)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:105)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:101)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:93)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:82)

Code for read model:

public static BimServerClient getclient(String url, String user, String passwd) {
    try {
        JsonBimServerClientFactory factory = new JsonBimServerClientFactory(url);
        try (BimServerClient client = factory.create(new UsernamePasswordAuthenticationInfo(user, passwd))) {
            return client;
        } catch (org.bimserver.shared.exceptions.UserException ex) {
            IO.outerror("Benutzername oder Passwort wurde nicht akzeptiert!", "Fehler bei Verbindung");
            return null;
        } catch (org.bimserver.shared.reflector.ReflectorException ex) {
            IO.outerror("Server konnte nicht gefunden werden!", "Fehler bei Verbindung");
            return null;
        } catch (Exception ex) {
            IO.outerror(ex.getMessage(), "Fehler bei Verbindung");
            return null;
        }
    } catch (BimServerClientException ex) {
        Logger.getLogger(Utils.class.getName()).log(Level.SEVERE, null, ex);
        return null;
    }
}

 public void setproject(org.bimserver.interfaces.objects.SProject project) {
    this.project = project;
    setisifc();
    if (project.getLastRevisionId() < 0) {
        return;
    }
    javax.swing.JDialog d = createwait();
    try {
        model = client.getModel(project, project.getLastRevisionId(), true, true, true);
        if (isifc2()) {
            ifc2ProductList = model.getAllWithSubTypes(org.bimserver.models.ifc2x3tc1.IfcProduct.class);
        }
        if (isifc4()) {
            ifc4ProductList = model.getAllWithSubTypes(org.bimserver.models.ifc4.IfcProduct.class);
        }
    } catch (UserException | ServerException ex) {
        Logger.getLogger(globalsets.class.getName()).log(Level.SEVERE, null, ex);
    }
    d.dispose();
}

Code for commit:

private void jButtoncommitActionPerformed(java.awt.event.ActionEvent evt) {                                              
    try {
        String comtext = JOptionPane.showInputDialog("Bitte Text für commit eingeben:  ");
        if (comtext == null) {
            return;
        }
        IO.o("TransactionID: " + globalset.getmodel().getTransactionId());
        globalset.getmodel().fixOidCounter();
        globalset.getmodel().fixOids();
        //globalset.getmodel().fixInverseMismatches();

        //globalset.getmodel().checkDoubleOidsPlusReferences();
        //globalset.getclient().commit(globalset.getmodel(), comtext);
       // globalset.getmodel().checkin(globalset.getproject().getRid(), comtext);
        javax.swing.JDialog d = globalset.createwait("Daten werden auf den Bimserver übertragen!");
        IO.o(globalset.getmodel().commit(comtext));
        d.dispose();
        IO.o("commited");
        IO.o(globalset.getmodel().getTransactionId());
        d = globalset.createwait("Model des Bimservers wird neu geladen!");
        //model = client.getModel(project, project.getLastRevisionId(), true, true, true);
        globalset.setmodel(globalset.getclient().getModel(globalset.getproject(), 
        globalset.getproject().getLastRevisionId(), true, true));
        d.dispose();
        IO.o(globalset.getmodel().getTransactionId());
    } catch (ServerException ex) {
        Logger.getLogger(ifcGUI.class.getName()).log(Level.SEVERE, null, ex);
    } catch (UserException ex) {
        Logger.getLogger(ifcGUI.class.getName()).log(Level.SEVERE, null, ex);
    } catch (PublicInterfaceNotFoundException ex) {
        Logger.getLogger(ifcGUI.class.getName()).log(Level.SEVERE, null, ex);
    } catch (BimServerClientException ex) {
        Logger.getLogger(ifcGUI.class.getName()).log(Level.SEVERE, null, ex);
    }
}                                             

Играя в Minecraft и вообще, пользуясь приложениями, написанными на Java Вы не раз могли столкнуться с ошибками (исключениями). В отличие от других языков программирования, Java жёстко заточена под использование ООП, потому при возникновении ошибки бросается исключение (объект содержащий сведения под ошибке). Его можно «поймать», дабы предпринять какие-то действия (допустим, вывести в лог). В случае майнкрафта, при возникновении исключения, создаётся краш-отчёт и работа игры завершается.

Понять исключения достаточно просто и вам для этого не понадобится специальное ПО для отладки.

2017-10-03_153645.png

Полная печать исключения состоит из 3-х частей:

  1. Исключение — имя класса ошибки. Классам обычно дают понятные человеку имена, достаточно знаний английского, чтобы понять значение.
  2. Сообщение — содержит более детальное описание ошибки. Может отсутствовать.
  3. Стек вызова — отражает ход работы программы (снизу вверх). Данная информация больше полезна разработчику, дабы понять, где именно возникла ошибка. Обычному пользователю данная информация может помочь понять, с чем связана ошибка (по именам классов и вызываемым функциям — методам).

Исключения могут иметь предков, что присутствует в данном примере (после «Caused by» идёт печать исключения-предка). Если вам не понятно исключение, возможно, стоит рассмотреть его предков — они могут содержать более понятное сообщение.

В данной теме я опишу наиболее часто встречающиеся ошибки, а также, какие действия следует или вовсе не следует предпринимать. Причин у ошибок множество и это не всегда повреждённые файлы игры (чего быть в принципе не может, поскольку лаунчер проверяет файлы игры).

При возникновении ошибок не спешите бежать переустанавливать Java и игру! Java — стабильный продукт. В большинстве случаев, ошибки возникают из-за неправильной настройки ОС; ошибок сети; неправильных драйверов.

org.lwjgl.LWJGLException: Pixel format not accelerated
Недоступно аппаратное ускорение графики. Описание ошибки (англ.)

Решение: Установите последнюю версию драйвера видеокарты.

javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path validation/building failed
Не удаётся установить защищённое соединение из-за невозможности проверки SSL сертификата.

Что можно сделать:

  • Эта ошибка может возникнуть из-за использования слишком старой версии Java. Рекомендуется регулярно обновлять ПО, чтобы иметь актуальный список корневых сертификатов.
  • Виновником может быть антивирус, пытающийся «подсунуть» свой сертификат с целью прослушивания трафика. Настоятельно рекомендуется отключить в антивирусе проверку защищённых соединений (HTTPS/SSL/TLS) — это значительно снижает безопасность защищённых соединений и вызывает проблемы в работе приложений, использующие их.

java.net.SocketTimeOutException: Read timed out
Ошибка сети «время ожидания истекло». Здесь сложно установить виновника: проблема может быть как на стороне сервера, вашего провайдера или вызвана антивирусом.

Что можно сделать:

  • Отключите антивирус и попробуйте выполнить запрос снова.
  • Используйте другое подключение к интернету (другой провайдер; мобильный интернет; VPN; Wi-Fi соседей).
  • Используйте VPN для обхода блокировки (цензуры) со стороны вашего интернет-провайдера.

java.net.ConnectException: Connection timed out: connect
Ошибка сети — не удалось установить соединение с хостом. Обычно виновником данной ошибки является Firewall (брандмауэр) или отсутствие интернета.

Что можно сделать:

  • Проверьте наличие подключения к интернету.
  • Временно отключите антивирус и Firewall.

java.net.SocketException: Connection reset / Удаленный хост принудительно разорвал существующее подключение
Ошибка сети «соединение сброшено». Как и в предыдущей ошибке, проблема связана с «плохим» интернетом, либо проблемами на стороне сервера (в этом случае ошибка будет у всех). Чаще всего возникает у пользователей мобильного интернета (USB-модем). От вас никаких действий предпринимать не требуется, кроме как найти «другой интернет» или использовать VPN для обхода фильтра сайтов.

java.lang.ClassCastException: XXX cannot be cast to YYY
Ошибка в логике программы: попытка привести объект к классу, экземпляром коего объект не является.

Решение: Сообщите о проблеме разработчику программы, приложив лог ошибки.

java.io.IOException: Server returned HTTP response code: 000 for URL
Проблема на стороне веб-сервера. Стандартная библиотека Java выбрасывает исключение, если веб-сервер выдаёт, например, страницу «404 Not Found».

Решение: Сообщите о проблеме владельцу веб-сервера, URL которого указан в тексте ошибки.

java.lang.UnsatisfiedLinkError: Can’t load library:
Не удалось загрузить нативную библиотеку (скорее всего, отсутствует файл по указанному пути).

Что можно сделать:

  • Чаще всего ошибка возникает из-за отсутствия библиотек LWJGL. Почему их файлы пропадают, пока остаётся загадкой. Если пути вы видите «.redserver/natives/2.9.1/lwjgl.dll», значит надо удалить папку natives, находящуюся в .redserver, чтобы лаунчер их скачал заново.
    Неактуально: С версии 3.2 лаунчер проверяет наличие всех файлов и автоматически, при необходимости, перекачивает их.

java.lang.RuntimeException: Unknown character in
Синтаксическая ошибка в конфигурационном файле мода.

Что можно сделать:

  • Удалите указанный в ошибке файл. Мод создаст новый с настройками по умолчанию.
  • Если вам сложно удалить файл, можно сделать сброс конфигов через лаунчер. Нажмите в лаунчере на многоточие на кнопке «Играть»; выберите в меню пункт «Очистка клиента»; установите флажок возле «Сбросить конфигурацию» и запустите очистку.
  • Выполните проверку диска на наличие ошибок. Испорченные файлы могут быть признаком неисправности диска.

java.lang.NullPointerException (NPE)
Ошибка в логике программы: попытка вызвать нестатичный метод, обратиться к полю несуществующего объекта — null.

Решение: Сообщите о проблеме разработчику программы, приложив лог ошибки.

java.net.UnknownHostException
Ошибка сети: не удаётся определить IP-адрес доменного имени (в общем, проблемы с DNS).

Что можно сделать:

  • Иногда ошибка может возникать, если вы не подключены к интернету, либо же произошёл разрыв интернет-соединения. Обычно исчезает сама через небольшой промежуток времени после возобновления соединения. Если ошибка не исчезла — может помочь перезагрузка компьютера (сбрасывает кеш DNS).
  • Доступ к ресурсу заблокирован вашим провайдером. Сейчас данная проблема актуальна для украинских пользователей: используемый нами Яндекс.DNS заблокирован в этой стране. Читайте, как обойти блокировку DNS.

java.io.EOFException: Unexpected end of ZLIB input stream
Неожиданный конец файла. В данном случае — ZIP-архива. Возникает например, когда вы пытаетесь распаковать недокачанный архив.

java.net.SocketException: Address family not supported by protocol family: connect
Проблема возникает из-за неправильной настройки протокола IPv6. Если таковой не поддерживается вашим интернет-провайдером, его поддержку следует отключить.

image.png

java.lang.OutOfMemoryError
А вот это как раз «любимая» ошибка про нехватку ОЗУ. Не стоит сразу спешить выставлять память в лаунчере на максимум, потому что дальнейшие действия зависят от сообщения к ошибке:

  • Unable to create new native thread / Metaspace — в вашей системе закончились ресурсы (ОЗУ). Решается только путём завершения всех лишних программ, либо апгрейдом ПК (больше ОЗУ — больше программ можно запустить). Не забывайте, что следует использовать 64-разрядную систему.
  • Java heap space — нехватка размера heap области памяти. Увеличьте лимит памяти в настройках лаунчера.

Problem

The Modeler .str file has become corrupt. No recovery exists for the explicit file. If no further action is done within Modeler, the backup .str- file may be intact.

Symptom

«Unexpected end of ZLIB input stream»

Cause

The error message means that the stream file is invalid. The compression procedure involved in creating a stream file is performed by the Java Virtual Machine that is responsible for handling the User Interface. If Modeler Client is closed before the stream has finished saving, then the resulting stream file will be incomplete. To date this problem has been reported only on a few occasions and the lack of available information into the environment leading up to this problem means the problem has not been replicated. If you see Modeler client using a lot of RAM (that the two numbers in the bottom right-hand-corner of the Modeler workpane are very close to each other), then it is possible that saving a large stream within that session will take a significant amount of time as the JVM is using as much memory as it is currently allowed to. In this situation please allow the stream save process to complete — the presence of the hourglass cursor within Modeler client for an extended time in this situation does not indicate an application hang and therefore does not indicate in itself the need for a forceful termination of the process.

We are investigating if we can make it clearer to the user that the stream save is still in progress.

Note it is possible for external factors to corrupt Modeler streams just as they can corrupt any files. If you have Modeler streams that suddenly appear corrupt, but Modeler hasn’t been used to load or save them since previously successful use, then it is likely that something external has corrupted the files on your filesystem. If this is the case please restore the files from backup as you would in the event of corruption of any other file types.

Resolving The Problem

If you experience this issue the stream cannot be recovered, although the backup stream of the same name (but with suffix ‘.str-‘) should be intact. Please delete the corrupted original and use the previous backup stream.

If you have a specific stream that causes this when you attempt to reload it, and the save within Modeler appears to complete (ie. the UI returns for use from the busy hourglass cursor), then please, if possible, follow these steps:

1. Copy the backup stream in Windows explorer (the stream with the same name but with the «.str-» extension to , eg. «mybackup.str» — retain this stream as a master backup).
2. open the backup stream (with the same name as the original stream but a «.str-» extension)
3. document the exact steps that were taken to modify the backup stream so that it is in the exact state it was in immediately before the final save that created the stream file that you can no longer load without this error.
4. Confirm that it is repeatable (ie. confirm that if you again save the stream that you get the same error when you try to reload it into Modeler)
5. If it is, please provide the backup stream, «my backup.str» along with the documentation of the steps you made in step 3. so we can attempt to replicate the issue.

Related Information

[{«Product»:{«code»:»SS3RA7″,»label»:»IBM SPSS Modeler»},»Business Unit»:{«code»:»BU059″,»label»:»IBM Software w/o TPS»},»Component»:»Modeler»,»Platform»:[{«code»:»PF033″,»label»:»Windows»}],»Version»:»Not Applicable»,»Edition»:»All Editions;Workstation»,»Line of Business»:{«code»:»LOB10″,»label»:»Data and AI»}}]

I get a Unexpected end of ZLIB input stream error when I try to read a model, I committed before. I have tried the SingleCheckinAndDownload.java example and the error occurs to. After a commit the 3D-view in bimviews does also not work. There is only the loading project bar but without progress. Is there something wrong with my code or is there a problem with the server?

Error :

[AWT-EventQueue-0] INFO org.bimserver.emf.SharedJsonDeserializer — # Objects: 1772
java.io.EOFException: Unexpected end of ZLIB input stream
at java.util.zip.InflaterInputStream.fill(InflaterInputStream.java:240)
at java.util.zip.InflaterInputStream.read(InflaterInputStream.java:158)
at java.util.zip.GZIPInputStream.read(GZIPInputStream.java:117)
at java.io.FilterInputStream.read(FilterInputStream.java:107)
at org.apache.http.client.entity.LazyDecompressingInputStream.read(LazyDecompressingInputStream.java:67)
at org.apache.commons.io.IOUtils.copyLarge(IOUtils.java:1792)
at org.apache.commons.io.IOUtils.copyLarge(IOUtils.java:1769)
at org.apache.commons.io.IOUtils.copy(IOUtils.java:1744)
at org.bimserver.client.ClientIfcModel.loadGeometry(ClientIfcModel.java:347)
at org.bimserver.client.ClientIfcModel.loadDeep(ClientIfcModel.java:303)
at org.bimserver.client.ClientIfcModel.(ClientIfcModel.java:115)
at org.bimserver.client.BimServerClient.getModel(BimServerClient.java:202)
at at.ac.get.opensourcebimeditor.globalsets.setproject(globalsets.java:316)
at at.ac.get.opensourcebimeditor.globalsets.setproject(globalsets.java:491)
at at.ac.get.opensourcebimeditor.GUI.ProjectGUI.jComboBox1ActionPerformed(ProjectGUI.java:410)
at at.ac.get.opensourcebimeditor.GUI.ProjectGUI.access$000(ProjectGUI.java:30)
at at.ac.get.opensourcebimeditor.GUI.ProjectGUI$1.actionPerformed(ProjectGUI.java:147)
at javax.swing.JComboBox.fireActionEvent(JComboBox.java:1258)
at javax.swing.JComboBox.setSelectedItem(JComboBox.java:586)
at javax.swing.JComboBox.setSelectedIndex(JComboBox.java:622)
at javax.swing.plaf.basic.BasicComboPopup$Handler.mouseReleased(BasicComboPopup.java:861)
at java.awt.AWTEventMulticaster.mouseReleased(AWTEventMulticaster.java:290)
at java.awt.Component.processMouseEvent(Component.java:6533)
at javax.swing.JComponent.processMouseEvent(JComponent.java:3324)
at javax.swing.plaf.basic.BasicComboPopup$1.processMouseEvent(BasicComboPopup.java:510)
at java.awt.Component.processEvent(Component.java:6298)
at java.awt.Container.processEvent(Container.java:2236)
at java.awt.Component.dispatchEventImpl(Component.java:4889)
at java.awt.Container.dispatchEventImpl(Container.java:2294)
at java.awt.Component.dispatchEvent(Component.java:4711)
at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4888)
at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4525)
at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4466)
at java.awt.Container.dispatchEventImpl(Container.java:2280)
at java.awt.Window.dispatchEventImpl(Window.java:2746)
at java.awt.Component.dispatchEvent(Component.java:4711)
at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:758)
at java.awt.EventQueue.access$500(EventQueue.java:97)
at java.awt.EventQueue$3.run(EventQueue.java:709)
at java.awt.EventQueue$3.run(EventQueue.java:703)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:80)
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:90)
at java.awt.EventQueue$4.run(EventQueue.java:731)
at java.awt.EventQueue$4.run(EventQueue.java:729)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:80)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:728)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:201)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:116)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:105)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:101)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:93)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:82)

Code for read model:

public static BimServerClient getclient(String url, String user, String passwd) {
    try {
        JsonBimServerClientFactory factory = new JsonBimServerClientFactory(url);
        try (BimServerClient client = factory.create(new UsernamePasswordAuthenticationInfo(user, passwd))) {
            return client;
        } catch (org.bimserver.shared.exceptions.UserException ex) {
            IO.outerror("Benutzername oder Passwort wurde nicht akzeptiert!", "Fehler bei Verbindung");
            return null;
        } catch (org.bimserver.shared.reflector.ReflectorException ex) {
            IO.outerror("Server konnte nicht gefunden werden!", "Fehler bei Verbindung");
            return null;
        } catch (Exception ex) {
            IO.outerror(ex.getMessage(), "Fehler bei Verbindung");
            return null;
        }
    } catch (BimServerClientException ex) {
        Logger.getLogger(Utils.class.getName()).log(Level.SEVERE, null, ex);
        return null;
    }
}

 public void setproject(org.bimserver.interfaces.objects.SProject project) {
    this.project = project;
    setisifc();
    if (project.getLastRevisionId() < 0) {
        return;
    }
    javax.swing.JDialog d = createwait();
    try {
        model = client.getModel(project, project.getLastRevisionId(), true, true, true);
        if (isifc2()) {
            ifc2ProductList = model.getAllWithSubTypes(org.bimserver.models.ifc2x3tc1.IfcProduct.class);
        }
        if (isifc4()) {
            ifc4ProductList = model.getAllWithSubTypes(org.bimserver.models.ifc4.IfcProduct.class);
        }
    } catch (UserException | ServerException ex) {
        Logger.getLogger(globalsets.class.getName()).log(Level.SEVERE, null, ex);
    }
    d.dispose();
}

Code for commit:

private void jButtoncommitActionPerformed(java.awt.event.ActionEvent evt) {                                              
    try {
        String comtext = JOptionPane.showInputDialog("Bitte Text für commit eingeben:  ");
        if (comtext == null) {
            return;
        }
        IO.o("TransactionID: " + globalset.getmodel().getTransactionId());
        globalset.getmodel().fixOidCounter();
        globalset.getmodel().fixOids();
        //globalset.getmodel().fixInverseMismatches();

        //globalset.getmodel().checkDoubleOidsPlusReferences();
        //globalset.getclient().commit(globalset.getmodel(), comtext);
       // globalset.getmodel().checkin(globalset.getproject().getRid(), comtext);
        javax.swing.JDialog d = globalset.createwait("Daten werden auf den Bimserver übertragen!");
        IO.o(globalset.getmodel().commit(comtext));
        d.dispose();
        IO.o("commited");
        IO.o(globalset.getmodel().getTransactionId());
        d = globalset.createwait("Model des Bimservers wird neu geladen!");
        //model = client.getModel(project, project.getLastRevisionId(), true, true, true);
        globalset.setmodel(globalset.getclient().getModel(globalset.getproject(), 
        globalset.getproject().getLastRevisionId(), true, true));
        d.dispose();
        IO.o(globalset.getmodel().getTransactionId());
    } catch (ServerException ex) {
        Logger.getLogger(ifcGUI.class.getName()).log(Level.SEVERE, null, ex);
    } catch (UserException ex) {
        Logger.getLogger(ifcGUI.class.getName()).log(Level.SEVERE, null, ex);
    } catch (PublicInterfaceNotFoundException ex) {
        Logger.getLogger(ifcGUI.class.getName()).log(Level.SEVERE, null, ex);
    } catch (BimServerClientException ex) {
        Logger.getLogger(ifcGUI.class.getName()).log(Level.SEVERE, null, ex);
    }
}                                             

Error message

Test environment, a file reading function reports an error, the error log is as follows

java.io.IOException: Failed to read zip entry source

 at org.apache.poi.openxml4j.opc.ZipPackage.<init>(ZipPackage.java:103)
 at org.apache.poi.openxml4j.opc.OPCPackage.open(OPCPackage.java:324)
 at org.apache.poi.ss.usermodel.WorkbookFactory.create(WorkbookFactory.java:185)
 at org.apache.poi.ss.usermodel.WorkbookFactory.create(WorkbookFactory.java:144)
 at com.wwwarehouse.xdw.commonindustry.manager.impl.importConvert.templateList.GoodsConvertImpl.cloneExcelTemplate(GoodsConvertImpl.java:406)
 at com.wwwarehouse.xdw.commonindustry.manager.impl.importConvert.templateList.GoodsConvertImpl.genErrorExcelBytes(GoodsConvertImpl.java:299)
 at com.wwwarehouse.xdw.commonindustry.service.dubbo.DubboServiceTest.importGoods(DubboServiceTest.java:84)
 at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
 at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
 at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
 at java.lang.reflect.Method.invoke(Method.java:498)
 at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
 at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
 at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
 at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
 at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:75)
 at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:86)
 at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:84)
 at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
 at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:252)
 at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:94)
 at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
 at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
 at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
 at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
 at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
 at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
 at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
 at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
 at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:191)
 at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
 at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
 at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:47)
 at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242)
 at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)
Caused by: java.io.EOFException: Unexpected end of ZLIB input stream
 at java.util.zip.InflaterInputStream.fill(InflaterInputStream.java:240)
 at java.util.zip.InflaterInputStream.read(InflaterInputStream.java:158)
 at java.util.zip.ZipInputStream.read(ZipInputStream.java:194)
 at org.apache.poi.openxml4j.util.ZipSecureFile$ThresholdInputStream.read(ZipSecureFile.java:213)
 at java.io.FilterInputStream.read(FilterInputStream.java:107)
 at org.apache.poi.openxml4j.util.ZipInputStreamZipEntrySource$FakeZipEntry.<init>(ZipInputStreamZipEntrySource.java:132)
 at org.apache.poi.openxml4j.util.ZipInputStreamZipEntrySource.<init>(ZipInputStreamZipEntrySource.java:56)
 at org.apache.poi.openxml4j.opc.ZipPackage.<init>(ZipPackage.java:100)
 ... 34 more

The corresponding source code is as follows:

InputStream is = ...
int available = is.available();
byte[] fileBytes = new byte[available];
int read = is.read(fileBytes);

The file fails to create a file based on fileBytes. The above error is reported.

Troubleshoot

There is no problem when verifying locally. I checked it online and said that the stream object is not closed and the reading is incomplete.
Checked the code, the input stream did not close. As an old driver, he condemned himself.
But with the stream closing action added, the problem remains.

Added log information output:

InputStream is = ...
int available = is.available();
byte[] fileBytes = new byte[available];
int read = is.read(fileBytes);
log.info("read:" + read + ", available:" + available);

Local execution, ok, read and available are consistent.
The test environment runs, and the print log is as follows: read:9608, available:54192
Why the content read is not the same as the available, check the comment of the read method in the InputStream.
The method returns the actual read length, and it is possible to read the length of the byte array at most. Instead of thinking that I must read the length of the byte array.

Modified the read code, the problem is solved

import org.apache.commons.io.IOUtils;
...

byte[] fileBytes = IOUtils.toByteArray(is);

The tool class implementation principle is as follows ():

byte[] buffer = new byte[1024];
int len = 0;
ByteArrayOutputStream bos = new ByteArrayOutputStream();
while((len = inputStream.read(buffer)) != -1) {
     bos.write(buffer, 0, len);
}
bos.close();
return bos.toByteArray();

Why is this problem?

A brief review of the operating system content, understand as follows:
Operating system content has segmental, page-based memory management. Memory is more expensive than cheaper disks. When the operating system loads content from external to memory, it is not necessary to load everything into memory.
Otherwise, if the application size is larger than the memory, it will not be executed.
For example, page memory management, allocate space by page, load page by file when accessing file, if it can directly hit, return hit content, otherwise it will generate page fault interrupt and read from disk again.
The server we deployed is a Linux virtual machine. I guess the access disk is directly accessed by my local physical machine. There are more levels of IO mapping, and there is a gap in the reading process.
gets the first part of the content, not all of it.

Understand the fur, it is rough. Interested students can turn over the memory management and IO principles of the operating system.

Attached, source code comments for the InputStream.read method (jdk1.8)

/**
 ... Slightly, see the method annotation below
 */
public int read(byte b[]) throws IOException {
    return read(b, 0, b.length);
}

/**
 * Reads up to <code>len</code> bytes of data from the input stream into
 * an array of bytes.  An attempt is made to read as many as
 * <code>len</code> bytes, but a smaller number may be read.
 * The number of bytes actually read is returned as an integer.
 *
 * <p> This method blocks until input data is available, end of file is
 * detected, or an exception is thrown.
 *
 * <p> If <code>len</code> is zero, then no bytes are read and
 * <code>0</code> is returned; otherwise, there is an attempt to read at
 * least one byte. If no byte is available because the stream is at end of
 * file, the value <code>-1</code> is returned; otherwise, at least one
 * byte is read and stored into <code>b</code>.
 *
   Note the following paragraph, assuming k is the actual number of bytes read, the content read will be filled to b[off] to b[off+k-1], b[off+k] to b[off +len-1]maintained
 * <p> The first byte read is stored into element <code>b[off]</code>, the
 * next one into <code>b[off+1]</code>, and so on. The number of bytes read
 * is, at most, equal to <code>len</code>. Let <i>k</i> be the number of
 * bytes actually read; these bytes will be stored in elements
 * <code>b[off]</code> through <code>b[off+</code><i>k</i><code>-1]</code>,
 * leaving elements <code>b[off+</code><i>k</i><code>]</code> through
 * <code>b[off+len-1]</code> unaffected.
 *
 * <p> In every case, elements <code>b[0]</code> through
 * <code>b[off]</code> and elements <code>b[off+len]</code> through
 * <code>b[b.length-1]</code> are unaffected.
 *
 * <p> The <code>read(b,</code> <code>off,</code> <code>len)</code> method
 * for class <code>InputStream</code> simply calls the method
 * <code>read()</code> repeatedly. If the first such call results in an
 * <code>IOException</code>, that exception is returned from the call to
 * the <code>read(b,</code> <code>off,</code> <code>len)</code> method.  If
 * any subsequent call to <code>read()</code> results in a
 * <code>IOException</code>, the exception is caught and treated as if it
 * were end of file; the bytes read up to that point are stored into
 * <code>b</code> and the number of bytes read before the exception
 * occurred is returned. The default implementation of this method blocks
 * until the requested amount of input data <code>len</code> has been read,
 * end of file is detected, or an exception is thrown. Subclasses are encouraged
 * to provide a more efficient implementation of this method.
 *
 * @param      b     the buffer into which the data is read.
 * @param      off   the start offset in array <code>b</code>
 *                   at which the data is written.
   * @param len the maximum number of bytes to read. --- Read most len
 * @return     the total number of bytes read into the buffer, or
 *             <code>-1</code> if there is no more data because the end of
   * the stream has been reached. --- The length of the actual read
 * @exception  IOException If the first byte cannot be read for any reason
 * other than end of file, or if the input stream has been closed, or if
 * some other I/O error occurs.
 * @exception  NullPointerException If <code>b</code> is <code>null</code>.
 * @exception  IndexOutOfBoundsException If <code>off</code> is negative,
 * <code>len</code> is negative, or <code>len</code> is greater than
 * <code>b.length - off</code>
 * @see        java.io.InputStream#read()
 */
public int read(byte b[], int off, int len) throws IOException {
...
}

Reference material

Что-то не так с GZIPInputStream или GZIPOutputStream. Просто прочитайте следующий код (или запустите его и посмотрите, что произойдет):

def main(a: Array[String]) {
    val name = "test.dat"
    new GZIPOutputStream(new FileOutputStream(name)).write(10)
    println(new GZIPInputStream(new FileInputStream(name)).read())
}

Создает файл test.dat, записывает однобайтное 10 форматирование по GZIP и считывает байт в том же файле в том же формате.

И вот что я получил от него:

Exception in thread "main" java.io.EOFException: Unexpected end of ZLIB input stream
    at java.util.zip.InflaterInputStream.fill(Unknown Source)
    at java.util.zip.InflaterInputStream.read(Unknown Source)
    at java.util.zip.GZIPInputStream.read(Unknown Source)
    at java.util.zip.InflaterInputStream.read(Unknown Source)
    at nbt.Test$.main(Test.scala:13)
    at nbt.Test.main(Test.scala)

По какой-то причине линия чтения кажется неправильной.

Я искал ошибку Unexpected end of ZLIB input stream и нашел некоторые отчеты об ошибках для Oracle, выпущенные в 2007-2010 годах. Таким образом, я думаю, ошибка все еще остается в некотором роде, но я не уверен, что мой код прав, поэтому позвольте мне опубликовать это здесь и послушать ваши советы. Спасибо!

4b9b3361

Ответ 1

Вы должны вызвать close() на GZIPOutputStream, прежде чем пытаться его прочитать. Окончательные байты файла будут записываться только тогда, когда файл фактически закрыт. (Это независимо от какой-либо явной буферизации в стеке вывода. Поток знает только, чтобы сжимать и записывать последние байты, когда вы приказываете закрыть его. flush(), вероятно, не поможет… хотя вызов finish() вместо close() должен работать. Посмотрите на javadocs.)

Здесь правильный код (в Java);

package test;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;

public class GZipTest {

    public static void main(String[] args) throws FileNotFoundException, IOException {
        String name = "/tmp/test";
        GZIPOutputStream gz = new GZIPOutputStream(new FileOutputStream(name));
        gz.write(10);
        gz.close();
        System.out.println(new GZIPInputStream(new FileInputStream(name)).read());
    }
}

(Я не правильно использовал управление ресурсами. Не рассматривайте это как пример «хорошего кода».)

  • Ошибка uniform 01 the division 2
  • Ошибка unexpected end of archive
  • Ошибка unicodeutf8 is not a member of qapplication
  • Ошибка unexpected character encountered while parsing value path line 0 position 0
  • Ошибка unhandled exception occurred see log for details dead air