Example usage for java.util.zip DataFormatException getMessage

List of usage examples for java.util.zip DataFormatException getMessage

Introduction

In this page you can find the example usage for java.util.zip DataFormatException getMessage.

Prototype

public String getMessage() 

Source Link

Document

Returns the detail message string of this throwable.

Usage

From source file:auth.ProcessResponseServlet.java

private String decodeAuthnRequestXML(String encodedRequestXmlString) throws SamlException {
    try {/*from   w  w w  . ja  va2  s. c  o m*/
        // URL decode
        // No need to URL decode: auto decoded by request.getParameter() method

        // Base64 decode
        Base64 base64Decoder = new Base64();
        byte[] xmlBytes = encodedRequestXmlString.getBytes("UTF-8");
        byte[] base64DecodedByteArray = base64Decoder.decode(xmlBytes);

        //Uncompress the AuthnRequest data
        //First attempt to unzip the byte array according to DEFLATE (rfc 1951)
        try {

            Inflater inflater = new Inflater(true);
            inflater.setInput(base64DecodedByteArray);
            // since we are decompressing, it's impossible to know how much space we
            // might need; hopefully this number is suitably big
            byte[] xmlMessageBytes = new byte[5000];
            int resultLength = inflater.inflate(xmlMessageBytes);

            if (!inflater.finished()) {
                throw new RuntimeException("didn't allocate enough space to hold " + "decompressed data");
            }

            inflater.end();
            return new String(xmlMessageBytes, 0, resultLength, "UTF-8");

        } catch (DataFormatException e) {

            // if DEFLATE fails, then attempt to unzip the byte array according to
            // zlib (rfc 1950)
            ByteArrayInputStream bais = new ByteArrayInputStream(base64DecodedByteArray);
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            InflaterInputStream iis = new InflaterInputStream(bais);
            byte[] buf = new byte[1024];
            int count = iis.read(buf);
            while (count != -1) {
                baos.write(buf, 0, count);
                count = iis.read(buf);
            }
            iis.close();
            return new String(baos.toByteArray());
        }

    } catch (UnsupportedEncodingException e) {
        throw new SamlException("Error decoding AuthnRequest: " + "Check decoding scheme - " + e.getMessage());
    } catch (IOException e) {
        throw new SamlException("Error decoding AuthnRequest: " + "Check decoding scheme - " + e.getMessage());
    }
}

From source file:org.apache.hadoop.mapred.TestConcatenatedCompressedInput.java

/**
 * Test using the raw Inflater codec for reading gzip files.
 *//*from  w w w  .  j av  a  2  s  . co  m*/
@Test
public void testPrototypeInflaterGzip() throws IOException {
    CompressionCodec gzip = new GzipCodec(); // used only for file extension
    localFs.delete(workDir, true); // localFs = FileSystem instance

    System.out.println(COLOR_BR_BLUE + "testPrototypeInflaterGzip() using "
            + "non-native/Java Inflater and manual gzip header/trailer parsing" + COLOR_NORMAL);

    // copy prebuilt (correct!) version of concat.gz to HDFS
    final String fn = "concat" + gzip.getDefaultExtension();
    Path fnLocal = new Path(System.getProperty("test.concat.data", "/tmp"), fn);
    Path fnHDFS = new Path(workDir, fn);
    localFs.copyFromLocalFile(fnLocal, fnHDFS);

    final FileInputStream in = new FileInputStream(fnLocal.toString());
    assertEquals("concat bytes available", 148, in.available());

    // should wrap all of this header-reading stuff in a running-CRC wrapper
    // (did so in BuiltInGzipDecompressor; see below)

    byte[] compressedBuf = new byte[256];
    int numBytesRead = in.read(compressedBuf, 0, 10);
    assertEquals("header bytes read", 10, numBytesRead);
    assertEquals("1st byte", 0x1f, compressedBuf[0] & 0xff);
    assertEquals("2nd byte", 0x8b, compressedBuf[1] & 0xff);
    assertEquals("3rd byte (compression method)", 8, compressedBuf[2] & 0xff);

    byte flags = (byte) (compressedBuf[3] & 0xff);
    if ((flags & 0x04) != 0) { // FEXTRA
        numBytesRead = in.read(compressedBuf, 0, 2);
        assertEquals("XLEN bytes read", 2, numBytesRead);
        int xlen = ((compressedBuf[1] << 8) | compressedBuf[0]) & 0xffff;
        in.skip(xlen);
    }
    if ((flags & 0x08) != 0) { // FNAME
        while ((numBytesRead = in.read()) != 0) {
            assertFalse("unexpected end-of-file while reading filename", numBytesRead == -1);
        }
    }
    if ((flags & 0x10) != 0) { // FCOMMENT
        while ((numBytesRead = in.read()) != 0) {
            assertFalse("unexpected end-of-file while reading comment", numBytesRead == -1);
        }
    }
    if ((flags & 0xe0) != 0) { // reserved
        assertTrue("reserved bits are set??", (flags & 0xe0) == 0);
    }
    if ((flags & 0x02) != 0) { // FHCRC
        numBytesRead = in.read(compressedBuf, 0, 2);
        assertEquals("CRC16 bytes read", 2, numBytesRead);
        int crc16 = ((compressedBuf[1] << 8) | compressedBuf[0]) & 0xffff;
    }

    // ready to go!  next bytes should be start of deflated stream, suitable
    // for Inflater
    numBytesRead = in.read(compressedBuf);

    // Inflater docs refer to a "dummy byte":  no clue what that's about;
    // appears to work fine without one
    byte[] uncompressedBuf = new byte[256];
    Inflater inflater = new Inflater(true);

    inflater.setInput(compressedBuf, 0, numBytesRead);
    try {
        int numBytesUncompressed = inflater.inflate(uncompressedBuf);
        String outString = new String(uncompressedBuf, 0, numBytesUncompressed, "UTF-8");
        System.out.println("uncompressed data of first gzip member = [" + outString + "]");
    } catch (java.util.zip.DataFormatException ex) {
        throw new IOException(ex.getMessage());
    }

    in.close();
}

From source file:org.atricore.idbus.capabilities.sso.main.binding.SamlR2HttpRedirectBinding.java

public static String inflateFromRedirect(String redirStr, boolean decode) throws Exception {

    if (redirStr == null || redirStr.length() == 0) {
        throw new RuntimeException("Redirect string cannot be null or empty");
    }//  w ww.ja  v  a2 s .c  o m

    byte[] redirBin = null;
    if (decode)
        redirBin = new Base64().decode(removeNewLineChars(redirStr).getBytes());
    else
        redirBin = redirStr.getBytes();

    // Decompress the bytes
    Inflater inflater = new Inflater(true);
    inflater.setInput(redirBin);

    ByteArrayOutputStream baos = new ByteArrayOutputStream(8192);

    try {
        int resultLength = 0;
        int buffSize = 1024;
        byte[] buff = new byte[buffSize];
        while (!inflater.finished()) {
            resultLength = inflater.inflate(buff);
            baos.write(buff, 0, resultLength);
        }

    } catch (DataFormatException e) {
        throw new RuntimeException("Cannot inflate SAML message : " + e.getMessage(), e);
    }

    inflater.end();

    // Decode the bytes into a String
    String outputString = null;
    try {
        outputString = new String(baos.toByteArray(), "UTF-8");
    } catch (UnsupportedEncodingException e) {
        throw new RuntimeException("Cannot convert byte array to string " + e.getMessage(), e);
    }
    return outputString;
}

From source file:org.barcelonamedia.uima.reader.DBXMIReader.DBXMICollectionReader.java

public void getNext(CAS aCAS) throws IOException, CollectionException {

    try {/* w ww  .  j  a va 2 s.  c  o m*/

        if (this.do_decompression) {

            //Create the decompressor and give it the data to compress
            Inflater decompressor = new Inflater();
            byte[] documentDataByteArray = IOUtils.toByteArray(this.documentData);

            decompressor.setInput(documentDataByteArray);

            //Create an expandable byte array to hold the decompressed data
            ByteArrayOutputStream bos = new ByteArrayOutputStream(documentDataByteArray.length);

            //Decompress the data
            byte[] buf = new byte[1024];

            while (!decompressor.finished()) {

                try {

                    int count = decompressor.inflate(buf);
                    bos.write(buf, 0, count);
                } catch (DataFormatException e) {

                    System.err.println("ERROR in Collection Reader " + e.getClass() + ": " + e.getMessage());
                    throw new IOException();
                }
            }

            try {

                bos.close();
            } catch (IOException e) {

                System.err.println("ERROR in Collection Reader " + e.getClass() + ": " + e.getMessage());
                throw new IOException();
            }

            //Get the decompressed data
            byte[] decompressedData = bos.toByteArray();

            XmiCasDeserializer.deserialize(new ByteArrayInputStream(decompressedData), aCAS,
                    !this.mFailOnUnknownType);
        } else {

            XmiCasDeserializer.deserialize(this.documentData, aCAS, !this.mFailOnUnknownType);
        }

        this.currentIndex += 1;
    } catch (SAXException e) {

        System.err.println("ERROR in Collection Reader " + e.getClass() + ": " + e.getMessage());
        throw new CollectionException(e);
    }
}

From source file:org.ow2.proactive.utils.ObjectByteConverter.java

/**
 * Convert the given byte array into the corresponding object.
 * <p>//from   www.j a v  a  2s  .  c  o m
 * The given byteArray can be uncompressed if it has been compressed before.
 * 
 * @param input the byteArray to be convert as an object.
 * @param uncompress true if the given byteArray must be also uncompressed, false if no compression was made on it.
 * @return the object corresponding to the given byteArray.
 * @throws IOException if an I/O exception occurs when writing the returned object
 * @throws ClassNotFoundException if class represented by given byteArray is not found.
 */
public static Object byteArrayToObject(byte[] input, boolean uncompress)
        throws IOException, ClassNotFoundException {
    if (input == null) {
        return null;
    }
    if (uncompress) {
        // Uncompress the bytes
        Inflater decompressor = new Inflater();
        decompressor.setInput(input);

        ByteArrayOutputStream bos = null;
        try {
            // Create an expandable byte array to hold the compressed data.
            bos = new ByteArrayOutputStream();
            // Compress the data
            byte[] buf = new byte[512];
            while (!decompressor.finished()) {
                int count = decompressor.inflate(buf);
                bos.write(buf, 0, count);
            }
            decompressor.end();
            // set the UNCOMPRESSED data
            input = bos.toByteArray();
        } catch (DataFormatException dfe) {
            //convert into io exception to fit previous behavior
            throw new IOException("Compressed data format is invalid : " + dfe.getMessage(), dfe);
        } finally {
            if (bos != null) {
                bos.close();
            }
        }
    }
    //here, input byteArray is uncompressed if needed
    ByteArrayInputStream bais = null;
    ObjectInputStream ois = null;
    try {
        bais = new ByteArrayInputStream(input);
        ois = new ObjectInputStream(bais);
        return ois.readObject();
    } finally {
        if (ois != null) {
            ois.close();
        }
        if (bais != null) {
            bais.close();
        }
    }
}

From source file:org.sakaiproject.tool.postem.PostemTool.java

public String processCreate() {

    try {/*from   w  ww.j  a v  a 2 s.  co m*/
        if (!this.checkAccess()) {
            throw new PermissionException(SessionManager.getCurrentSessionUserId(), "syllabus_access_athz", "");
        }

    } catch (PermissionException e) {
        // logger.info(this + ".getEntries() in PostemTool " + e);
        FacesContext.getCurrentInstance().addMessage(null, MessageUtils.getMessage(FacesMessage.SEVERITY_ERROR,
                "error_permission", (new Object[] { e.toString() }), FacesContext.getCurrentInstance()));
        this.currentGradebook = null;
        this.csv = null;
        this.newTemplate = null;
        // this.release = null;
        return "permission_error";
    }
    if (currentGradebook.getId() == null) {
        ArrayList gb = getGradebooks();
        Iterator gi = gb.iterator();
        while (gi.hasNext()) {
            if (((Gradebook) gi.next()).getTitle().equals(currentGradebook.getTitle())) {
                //To stay consistent, remove current messages when adding a new message
                //so as to only display one error message before returning
                PostemTool.clearMessages();
                PostemTool.populateMessage(FacesMessage.SEVERITY_ERROR, "duplicate_title", new Object[] {});
                return "create_gradebook";
            }
        }
    }
    if (currentGradebook.getTitle() == null || currentGradebook.getTitle().equals("")) {
        //To stay consistent, remove current messages when adding a new message
        //so as to only display one error message before returning
        PostemTool.clearMessages();
        PostemTool.populateMessage(FacesMessage.SEVERITY_ERROR, "missing_title", new Object[] {});
        return "create_gradebook";
    } else if (currentGradebook.getTitle().trim().length() > TITLE_MAX_LENGTH) {
        PostemTool.clearMessages();
        PostemTool.populateMessage(FacesMessage.SEVERITY_ERROR, "title_too_long", new Object[] {
                new Integer(currentGradebook.getTitle().trim().length()), new Integer(TITLE_MAX_LENGTH) });
        return "create_gradebook";
    }

    Reference attachment = getAttachmentReference();
    if (attachment == null) {
        return "create_gradebook";
    }

    if (!this.delimiter.equals(COMMA_DELIM_STR) && !this.delimiter.equals(TAB_DELIM_STR)) {
        PostemTool.populateMessage(FacesMessage.SEVERITY_ERROR, "invalid_delim", new Object[] {});
        return "create_gradebook";
    }

    if (attachment != null) {
        // logger.info("*** Non-Empty CSV!");
        try {

            char csv_delim = CSV.COMMA_DELIM;
            if (this.delimiter.equals(TAB_DELIM_STR)) {
                csv_delim = CSV.TAB_DELIM;
            }

            //Read the data

            ContentResource cr = contentHostingService.getResource(attachment.getId());
            //Check the type
            if (ResourceProperties.TYPE_URL.equalsIgnoreCase(cr.getContentType())) {
                //Going to need to read from a stream
                String csvURL = new String(cr.getContent());
                //Load the URL
                csv = URLConnectionReader.getText(csvURL);
                if (LOG.isDebugEnabled()) {
                    LOG.debug(csv);
                }
            } else {
                csv = new String(cr.getContent());
                if (LOG.isDebugEnabled()) {
                    LOG.debug(csv);
                }
            }
            CSV grades = new CSV(csv, withHeader, csv_delim);

            if (withHeader == true) {
                if (grades.getHeaders() != null) {

                    List headingList = grades.getHeaders();
                    for (int col = 0; col < headingList.size(); col++) {
                        String heading = (String) headingList.get(col).toString().trim();
                        // Make sure there are no blank headings
                        if (heading == null || heading.equals("")) {
                            PostemTool.populateMessage(FacesMessage.SEVERITY_ERROR, "blank_headings",
                                    new Object[] {});
                            return "create_gradebook";
                        }
                        // Make sure the headings don't exceed max limit
                        if (heading.length() > HEADING_MAX_LENGTH) {
                            PostemTool.populateMessage(FacesMessage.SEVERITY_ERROR, "heading_too_long",
                                    new Object[] { new Integer(HEADING_MAX_LENGTH) });
                            return "create_gradebook";
                        }
                    }
                }
            }

            if (grades.getStudents() != null) {
                if (!usernamesValid(grades)) {
                    return "create_gradebook";
                }

                if (hasADuplicateUsername(grades)) {
                    return "create_gradebook";
                }
            }

            if (this.newTemplate != null && this.newTemplate.trim().length() > 0) {
                if (this.newTemplate.trim().length() > TEMPLATE_MAX_LENGTH) {
                    PostemTool.populateMessage(FacesMessage.SEVERITY_ERROR, "template_too_long", new Object[] {
                            new Integer(this.newTemplate.trim().length()), new Integer(TEMPLATE_MAX_LENGTH) });
                    return "create_gradebook";
                }
            }

            if (withHeader == true) {
                if (grades.getHeaders() != null) {
                    PostemTool.populateMessage(FacesMessage.SEVERITY_INFO, "has_headers", new Object[] {});
                }
            }
            if (grades.getStudents() != null) {
                PostemTool.populateMessage(FacesMessage.SEVERITY_INFO, "has_students",
                        new Object[] { new Integer(grades.getStudents().size()) });
            }
            if (withHeader == true) {
                currentGradebook.setHeadings(grades.getHeaders());
            }
            List slist = grades.getStudents();

            if (oldGradebook.getId() != null && !this.userPressedBack) {
                Set oldStudents = currentGradebook.getStudents();
                oldGradebook.setStudents(oldStudents);
            }

            currentGradebook.setStudents(new TreeSet());
            // gradebookManager.saveGradebook(currentGradebook);
            Iterator si = slist.iterator();
            while (si.hasNext()) {
                List ss = (List) si.next();
                String uname = ((String) ss.remove(0)).trim();
                // logger.info("[POSTEM] processCreate -- adding student " +
                // uname);
                gradebookManager.createStudentGradesInGradebook(uname, ss, currentGradebook);
                if (currentGradebook.getStudents().size() == 1) {
                    currentGradebook.setFirstUploadedUsername(uname); //otherwise, the verify screen shows first in ABC order
                }
            }
        } catch (DataFormatException exception) {
            /*
             * TODO: properly subclass exception in order to allow for localized
             * messages (add getRowNumber/setRowNumber). Set exception message to be
             * key in .properties file
             */
            PostemTool.populateMessage(FacesMessage.SEVERITY_ERROR, exception.getMessage(), new Object[] {});
            return "create_gradebook";
        } catch (IdUnusedException e) {
            PostemTool.populateMessage(FacesMessage.SEVERITY_ERROR, e.getMessage(), new Object[] {});
            return "create_gradebook";
        } catch (TypeException e) {
            PostemTool.populateMessage(FacesMessage.SEVERITY_ERROR, e.getMessage(), new Object[] {});
            return "create_gradebook";
        } catch (PermissionException e) {
            PostemTool.populateMessage(FacesMessage.SEVERITY_ERROR, e.getMessage(), new Object[] {});
            return "create_gradebook";
        } catch (ServerOverloadException e) {
            PostemTool.populateMessage(FacesMessage.SEVERITY_ERROR, e.getMessage(), new Object[] {});
            return "create_gradebook";
        } catch (IOException e) {
            PostemTool.populateMessage(FacesMessage.SEVERITY_ERROR, e.getMessage(), new Object[] {});
            return "create_gradebook";
        }
    } else if (this.csv != null) {
        // logger.info("**** Non Null Empty CSV!");
        PostemTool.populateMessage(FacesMessage.SEVERITY_ERROR, "has_students",
                new Object[] { new Integer(0) });
        currentGradebook.setHeadings(new ArrayList());
        if (oldGradebook.getId() != null) {
            Set oldStudents = currentGradebook.getStudents();
            oldGradebook.setStudents(oldStudents);
        }

        currentGradebook.setStudents(new TreeSet());
    }

    if (this.newTemplate != null && this.newTemplate.trim().length() > 0) {
        currentGradebook.setTemplate(gradebookManager.createTemplate(newTemplate.trim()));
    } else if (this.newTemplate != null) {
        // logger.info("*** Non Null Empty Template!");
        currentGradebook.setTemplate(null);
    }

    /*
     * if("No".equals(this.release)) { currentGradebook.setReleased(new
     * Boolean(false)); //logger.info("Set to No, " +
     * currentGradebook.getReleased()); } else {
     * currentGradebook.setReleased(new Boolean(true)); //logger.info("Set to
     * Yes, " + currentGradebook.getReleased()); }
     */

    // gradebookManager.saveGradebook(currentGradebook);
    // logger.info(currentGradebook.getId());
    // currentGradebook = null;
    if ((this.csv != null && this.csv.trim().length() > 0)
            || (this.newTemplate != null && this.newTemplate.trim().length() > 0)) {
        this.csv = null;
        this.newTemplate = null;
        return "verify";
    }

    Iterator oi = oldGradebook.getStudents().iterator();
    while (oi.hasNext()) {
        gradebookManager.deleteStudentGrades((StudentGrades) oi.next());
    }
    this.userId = SessionManager.getCurrentSessionUserId();
    currentGradebook.setLastUpdated(new Timestamp(new Date().getTime()));
    currentGradebook.setLastUpdater(this.userId);
    gradebookManager.saveGradebook(currentGradebook);

    this.currentGradebook = null;
    this.oldGradebook = null;
    this.withHeader = true;
    // this.gradebooks = null;
    return "main";
}

From source file:servlets.ProcessResponseServlet.java

private String decodeAuthnRequestXML(String encodedRequestXmlString) throws SamlException {
    try {/*from www.  j  a v  a2 s . c o m*/
        // URL decode
        // No need to URL decode: auto decoded by request.getParameter() method

        // Base64 decode
        Base64 base64Decoder = new Base64();
        byte[] xmlBytes = encodedRequestXmlString.getBytes("UTF-8");
        byte[] base64DecodedByteArray = base64Decoder.decode(xmlBytes);

        //Uncompress the AuthnRequest data
        //First attempt to unzip the byte array according to DEFLATE (rfc 1951)
        try {

            Inflater inflater = new Inflater(true);
            inflater.setInput(base64DecodedByteArray);
            // since we are decompressing, it's impossible to know how much space we
            // might need; hopefully this number is suitably big
            byte[] xmlMessageBytes = new byte[5000];
            int resultLength = inflater.inflate(xmlMessageBytes);

            if (!inflater.finished()) {
                throw new RuntimeException("didn't allocate enough space to hold " + "decompressed data");
            }

            inflater.end();
            return new String(xmlMessageBytes, 0, resultLength, "UTF-8");

        } catch (DataFormatException e) {

            // if DEFLATE fails, then attempt to unzip the byte array according to
            // zlib (rfc 1950)      
            ByteArrayInputStream bais = new ByteArrayInputStream(base64DecodedByteArray);
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            InflaterInputStream iis = new InflaterInputStream(bais);
            byte[] buf = new byte[1024];
            int count = iis.read(buf);
            while (count != -1) {
                baos.write(buf, 0, count);
                count = iis.read(buf);
            }
            iis.close();
            return new String(baos.toByteArray());
        }

    } catch (UnsupportedEncodingException e) {
        throw new SamlException("Error decoding AuthnRequest: " + "Check decoding scheme - " + e.getMessage());
    } catch (IOException e) {
        throw new SamlException("Error decoding AuthnRequest: " + "Check decoding scheme - " + e.getMessage());
    }
}