Example usage for org.apache.commons.io IOExceptionWithCause IOExceptionWithCause

List of usage examples for org.apache.commons.io IOExceptionWithCause IOExceptionWithCause

Introduction

In this page you can find the example usage for org.apache.commons.io IOExceptionWithCause IOExceptionWithCause.

Prototype

public IOExceptionWithCause(String message, Throwable cause) 

Source Link

Document

Constructs a new instance with the given message and cause.

Usage

From source file:com.orange.mmp.api.ws.jsonrpc.MMPJsonRpcServlet.java

@Override
public void service(HttpServletRequest request, HttpServletResponse response) throws IOException {

    ExecutionContext executionContext = ExecutionContext.newInstance(request);
    executionContext.setName("JSON-RCP Request");

    executionContext.executionStart();//from w  ww.java2s .  c  o m
    String requestInfo = "";
    try {

        // Use protected method in case someone wants to override it
        JSONRPCBridge json_bridge = findBridge(request);

        // Encode using UTF-8, although We are actually ASCII clean as
        // all unicode data is JSON escaped using backslash u. This is
        // less data efficient for foreign character sets but it is
        // needed to support naughty browsers such as Konqueror and Safari
        // which do not honour the charset set in the response
        response.setContentType("application/json");
        response.setCharacterEncoding(Constants.DEFAULT_ENCODING);
        OutputStream out = response.getOutputStream();

        // Decode using the charset in the request if it exists otherwise
        // use UTF-8 as this is what all browser implementations use.
        // The JSON-RPC-Java JavaScript client is ASCII clean so it
        // although here we can correctly handle data from other clients
        // that do not escape non ASCII data
        String charset = request.getCharacterEncoding();
        if (charset == null) {
            charset = Constants.DEFAULT_ENCODING;
        }

        String receiveString = null;

        // Test HTTP GET
        if (request.getQueryString() != null) {
            String id = request.getParameter(HTTP_PARAM_ID);
            if (id != null) {
                executionContext.setApiName(id);

                StringBuilder receiveStringBuilder = new StringBuilder("{\"id\":").append(id)
                        .append(",\"method\":\"");
                String method = request.getParameter(HTTP_PARAM_METHOD);
                // Get params
                if (method != null) {
                    executionContext.setMethodName(method);

                    receiveStringBuilder.append(method);
                    String param = request.getParameter(HTTP_PARAM_PARAM);
                    // There is parameters
                    if (param != null) {
                        receiveStringBuilder.append("\",\"params\":").append(param).append("}");
                    }
                    // Empty params
                    else {
                        receiveStringBuilder.append("\",\"params\":[]}");
                    }
                }
                // Default method (list API)
                else {
                    receiveStringBuilder.append("system.listMethods\",\"params\":[]}");
                }

                // Set JSON-RPC call string
                receiveString = receiveStringBuilder.toString();

                //Trace request
                executionContext.setName("JSON-RCP Request: " + receiveString);
            }
        }

        // Test HTTP POST
        if (receiveString == null) {
            BufferedReader in = new BufferedReader(new InputStreamReader(request.getInputStream(), charset));

            // Read the request
            CharArrayWriter data = new CharArrayWriter();
            char buf[] = new char[4096];
            int ret;
            while ((ret = in.read(buf, 0, 4096)) != -1) {
                data.write(buf, 0, ret);
            }

            receiveString = data.toString();
            requestInfo = receiveString;
        }

        // Process the request
        JSONObject json_req;
        JSONRPCResult json_res;
        try {
            json_req = new JSONObject(receiveString);
            json_res = json_bridge.call(new Object[] { request, response }, json_req);
        } catch (JSONException e) {
            json_res = new JSONRPCResult(JSONRPCResult.CODE_ERR_PARSE, null, JSONRPCResult.MSG_ERR_PARSE);
        }

        String sendString = json_res.toString();

        // Write the response
        byte[] bout = sendString.getBytes(Constants.DEFAULT_ENCODING);

        // if the request header says that the browser can take gzip compressed
        // output, then gzip the output
        // but only if the response is large enough to warrant it and if the
        // resultant compressed output is
        // actually smaller.
        String ae = request.getHeader("accept-encoding");
        if (ae != null && ae.indexOf("gzip") != -1) {
            byte[] gzippedOut = gzip(bout);

            // if gzip didn't actually help, abort
            if (bout.length > gzippedOut.length) {
                bout = gzippedOut;
                response.addHeader("Content-Encoding", "gzip");
            }
        }

        response.setIntHeader("Content-Length", bout.length);

        out.write(bout);

    } catch (Throwable error) {
        //Catch exception
        throw new IOExceptionWithCause("Error during request processing", error);
    } finally {
        executionContext.executionStop();
        printMonitoredRequest(requestInfo);
        executionContext.close();
    }
}

From source file:de.innovationgate.wgpublisher.cache.WebTMLCache.java

public void dump(Writer out) throws IOException {
    out.write("DBKEY;TAGID;CACHEKEY;TIME;SIZE\n");
    DateFormat dateFormat = new SimpleDateFormat();
    try {/*  w  w  w .  ja  v  a 2  s.c om*/
        Iterator keys = _cache.getEntryKeys().iterator();
        while (keys.hasNext()) {
            String keyStr = (String) keys.next();
            try {
                CacheEntry entry = (CacheEntry) _cache.readEntry(keyStr);
                if (entry != null) {
                    CacheKey key = new CacheKey(keyStr);
                    out.write(key.getDbKey());
                    out.write(";");
                    out.write(key.getTagId());
                    out.write(";");
                    out.write(key.getExpressionKey());
                    out.write(";");
                    out.write(dateFormat.format(entry.getDate()));
                    out.write(";");
                    out.write(String.valueOf(((String) entry.getCode()).length()));
                    out.write("\n");
                }
            } catch (CacheException e) {
                out.write("Exception reading cache entry " + keyStr + ": " + e.getClass().getName() + " - "
                        + e.getMessage() + "\n");
                Logger.getLogger("wga.webtmlcache").error("Exception dumping WebTML cache entry " + keyStr, e);
            }
        }
    } catch (CacheException e) {
        throw new IOExceptionWithCause("Exception dumping WebTML Cache", e);
    }
}

From source file:org.apache.hive.hcatalog.api.repl.ReplicationUtils.java

/**
 * Command implements Writable, but that's not terribly easy to use compared
 * to String, even if it plugs in easily into the rest of Hadoop. Provide
 * utility methods to easily serialize and deserialize Commands
 *
 * deserializeCommand instantiates a concrete Command and initializes it,
 * given a base64 String representation of it.
 */// www .  j  a  v  a  2s.  c om
public static Command deserializeCommand(String s) throws IOException {
    DataInput dataInput = new DataInputStream(new ByteArrayInputStream(Base64.decodeBase64(s)));
    String clazz = (String) ReaderWriter.readDatum(dataInput);
    Command cmd;
    try {
        cmd = (Command) Class.forName(clazz).newInstance();
    } catch (Exception e) {
        throw new IOExceptionWithCause("Error instantiating class " + clazz, e);
    }
    cmd.readFields(dataInput);
    return cmd;
}

From source file:org.apache.jackrabbit.core.persistence.util.BundleNames.java

public static Name indexToName(int index) throws IOException {
    try {/*from   www . jav a2s.c  om*/
        return NAME_ARRAY[index];
    } catch (ArrayIndexOutOfBoundsException e) {
        throw new IOExceptionWithCause("Invalid common JCR name index: " + index, e);
    }
}

From source file:org.apache.jackrabbit.core.persistence.util.BundleReader.java

/**
 * Deserializes a <code>PropertyState</code> from the data input stream.
 *
 * @param id the property id for the new property entry
 * @return the property entry/*from   w  w w . ja va  2  s. c  om*/
 * @throws IOException if an I/O error occurs.
 */
private NodePropBundle.PropertyEntry readPropertyEntry(PropertyId id) throws IOException {
    NodePropBundle.PropertyEntry entry = new NodePropBundle.PropertyEntry(id);

    int count = 1;
    if (version >= BundleBinding.VERSION_3) {
        int b = in.readUnsignedByte();

        entry.setType(b & 0x0f);

        int len = b >>> 4;
        if (len != 0) {
            entry.setMultiValued(true);
            if (len == 0x0f) {
                count = readVarInt() + 0x0f - 1;
            } else {
                count = len - 1;
            }
        }

        entry.setModCount((short) readVarInt());
    } else {
        // type and modcount
        int type = in.readInt();
        entry.setModCount((short) ((type >> 16) & 0x0ffff));
        type &= 0x0ffff;
        entry.setType(type);

        // multiValued
        entry.setMultiValued(in.readBoolean());

        // definitionId
        in.readUTF();

        // count
        count = in.readInt();
    }

    // values
    InternalValue[] values = new InternalValue[count];
    String[] blobIds = new String[count];
    for (int i = 0; i < count; i++) {
        InternalValue val;
        int type = entry.getType();
        switch (type) {
        case PropertyType.BINARY:
            int size = in.readInt();
            if (size == BundleBinding.BINARY_IN_DATA_STORE) {
                val = InternalValue.create(binding.dataStore, readString());
            } else if (size == BundleBinding.BINARY_IN_BLOB_STORE) {
                blobIds[i] = readString();
                try {
                    BLOBStore blobStore = binding.getBlobStore();
                    if (blobStore instanceof ResourceBasedBLOBStore) {
                        val = InternalValue
                                .create(((ResourceBasedBLOBStore) blobStore).getResource(blobIds[i]));
                    } else {
                        val = InternalValue.create(blobStore.get(blobIds[i]));
                    }
                } catch (IOException e) {
                    if (binding.errorHandling.ignoreMissingBlobs()) {
                        log.warn("Ignoring error while reading blob-resource: " + e);
                        val = InternalValue.create(new byte[0]);
                    } else {
                        throw e;
                    }
                } catch (Exception e) {
                    throw new IOExceptionWithCause("Unable to create property value: " + e.toString(), e);
                }
            } else {
                // short values into memory
                byte[] data = new byte[size];
                in.readFully(data);
                val = InternalValue.create(data);
            }
            break;
        case PropertyType.DOUBLE:
            val = InternalValue.create(in.readDouble());
            break;
        case PropertyType.DECIMAL:
            val = InternalValue.create(readDecimal());
            break;
        case PropertyType.LONG:
            if (version >= BundleBinding.VERSION_3) {
                val = InternalValue.create(readVarLong());
            } else {
                val = InternalValue.create(in.readLong());
            }
            break;
        case PropertyType.BOOLEAN:
            val = InternalValue.create(in.readBoolean());
            break;
        case PropertyType.NAME:
            val = InternalValue.create(readQName());
            break;
        case PropertyType.WEAKREFERENCE:
            val = InternalValue.create(readNodeId(), true);
            break;
        case PropertyType.REFERENCE:
            val = InternalValue.create(readNodeId(), false);
            break;
        case PropertyType.DATE:
            if (version >= BundleBinding.VERSION_3) {
                val = InternalValue.create(readDate());
                break;
            } // else fall through
        default:
            if (version >= BundleBinding.VERSION_3) {
                val = InternalValue.valueOf(readString(), entry.getType());
            } else {
                // because writeUTF(String) has a size limit of 64k,
                // Strings are serialized as <length><byte[]>
                int len = in.readInt();
                byte[] bytes = new byte[len];
                in.readFully(bytes);
                String stringVal = new String(bytes, "UTF-8");

                // https://issues.apache.org/jira/browse/JCR-3083
                if (PropertyType.DATE == entry.getType()) {
                    val = InternalValue.createDate(stringVal);
                } else {
                    val = InternalValue.valueOf(stringVal, entry.getType());
                }
            }
        }
        values[i] = val;
    }
    entry.setValues(values);
    entry.setBlobIds(blobIds);

    return entry;
}

From source file:org.apache.jackrabbit.core.persistence.util.BundleWriter.java

/**
 * Serializes a property entry. The serialization begins with the
 * property name followed by a single byte that encodes the type and
 * multi-valuedness of the property://from   w ww  .  j a v a 2  s.c  o m
 * <pre>
 * +-------------------------------+
 * |   mv count    |     type      |
 * +-------------------------------+
 * </pre>
 * <p>
 * The lower four bits encode the property type (0-12 in JCR 2.0) and
 * higher bits indicate whether this is a multi-valued property and how
 * many property values there are. A value of 0 is reserved for
 * single-valued properties (that are guaranteed to always have just a
 * single value), and all non-zero values indicate a multi-valued property.
 * <p>
 * In multi-valued properties the exact value of the "mv count" field is
 * the number of property values plus one and truncated at 15 (the highest
 * four-bit value). If there are 14 or more (14 + 1 == 15) property values,
 * then the number of additional values is serialized as a variable-length
 * integer (see {@link #writeVarInt(int)}) right after this byte.
 * <p>
 * The modification count of the property state is written next as a
 * variable-length integer, followed by the serializations of all the
 * values of this property.
 *
 * @param state the property entry to store
 * @throws IOException if an I/O error occurs.
 */
private void writeState(NodePropBundle.PropertyEntry state) throws IOException {
    writeName(state.getName());

    InternalValue[] values = state.getValues();

    int type = state.getType();
    if (type < 0 || type > 0xf) {
        throw new IOException("Illegal property type " + type);
    }
    if (state.isMultiValued()) {
        int len = values.length + 1;
        if (len < 0x0f) {
            out.writeByte(len << 4 | type);
        } else {
            out.writeByte(0xf0 | type);
            writeVarInt(len - 0x0f);
        }
    } else {
        if (values.length != 1) {
            throw new IOException(
                    "Single values property with " + values.length + " values: " + state.getName());
        }
        out.writeByte(type);
    }

    writeVarInt(state.getModCount());

    // values
    for (int i = 0; i < values.length; i++) {
        InternalValue val = values[i];
        switch (type) {
        case PropertyType.BINARY:
            try {
                long size = val.getLength();
                if (val.isInDataStore()) {
                    out.writeInt(BundleBinding.BINARY_IN_DATA_STORE);
                    writeString(val.toString());
                } else if (binding.dataStore != null) {
                    writeSmallBinary(val, state, i);
                } else if (size < 0) {
                    log.warn("Blob has negative size. Potential loss of data. " + "id={} idx={}", state.getId(),
                            String.valueOf(i));
                    out.writeInt(0);
                    values[i] = InternalValue.create(new byte[0]);
                    val.discard();
                } else if (size > binding.getMinBlobSize()) {
                    // special handling required for binary value:
                    // spool binary value to file in blob store
                    out.writeInt(BundleBinding.BINARY_IN_BLOB_STORE);
                    String blobId = state.getBlobId(i);
                    if (blobId == null) {
                        BLOBStore blobStore = binding.getBlobStore();
                        try {
                            InputStream in = val.getStream();
                            try {
                                blobId = blobStore.createId(state.getId(), i);
                                blobStore.put(blobId, in, size);
                                state.setBlobId(blobId, i);
                            } finally {
                                IOUtils.closeQuietly(in);
                            }
                        } catch (Exception e) {
                            String msg = "Error while storing blob. id=" + state.getId() + " idx=" + i
                                    + " size=" + size;
                            log.error(msg, e);
                            throw new IOExceptionWithCause(msg, e);
                        }
                        try {
                            // replace value instance with value
                            // backed by resource in blob store and delete temp file
                            if (blobStore instanceof ResourceBasedBLOBStore) {
                                values[i] = InternalValue
                                        .create(((ResourceBasedBLOBStore) blobStore).getResource(blobId));
                            } else {
                                values[i] = InternalValue.create(blobStore.get(blobId));
                            }
                        } catch (Exception e) {
                            log.error("Error while reloading blob. truncating. id=" + state.getId() + " idx="
                                    + i + " size=" + size, e);
                            values[i] = InternalValue.create(new byte[0]);
                        }
                        val.discard();
                    }
                    // store id of blob as property value
                    writeString(blobId); // value
                } else {
                    // delete evt. blob
                    byte[] data = writeSmallBinary(val, state, i);
                    // replace value instance with value
                    // backed by resource in blob store and delete temp file
                    values[i] = InternalValue.create(data);
                    val.discard();
                }
            } catch (RepositoryException e) {
                String msg = "Error while storing blob. id=" + state.getId() + " idx=" + i + " value=" + val;
                log.error(msg, e);
                throw new IOExceptionWithCause(msg, e);
            }
            break;
        case PropertyType.DOUBLE:
            try {
                out.writeDouble(val.getDouble());
            } catch (RepositoryException e) {
                throw convertToIOException(type, e);
            }
            break;
        case PropertyType.DECIMAL:
            try {
                writeDecimal(val.getDecimal());
            } catch (RepositoryException e) {
                throw convertToIOException(type, e);
            }
            break;
        case PropertyType.LONG:
            try {
                writeVarLong(val.getLong());
            } catch (RepositoryException e) {
                throw convertToIOException(type, e);
            }
            break;
        case PropertyType.BOOLEAN:
            try {
                out.writeBoolean(val.getBoolean());
            } catch (RepositoryException e) {
                throw convertToIOException(type, e);
            }
            break;
        case PropertyType.NAME:
            try {
                writeName(val.getName());
            } catch (RepositoryException e) {
                throw convertToIOException(type, e);
            }
            break;
        case PropertyType.WEAKREFERENCE:
        case PropertyType.REFERENCE:
            writeNodeId(val.getNodeId());
            break;
        case PropertyType.DATE:
            try {
                writeDate(val.getCalendar());
            } catch (RepositoryException e) {
                throw convertToIOException(type, e);
            }
            break;
        case PropertyType.STRING:
        case PropertyType.PATH:
        case PropertyType.URI:
            writeString(val.toString());
            break;
        default:
            throw new IOException("Inknown property type: " + type);
        }
    }
}

From source file:org.apache.jackrabbit.core.persistence.util.BundleWriter.java

private static IOException convertToIOException(int propertyType, Exception e) {
    String typeName = PropertyType.nameFromValue(propertyType);
    String message = "Unexpected error for property type " + typeName + " value.";
    log.error(message, e);/*  w w  w .j  a  v  a 2  s .  c  om*/
    return new IOExceptionWithCause(message, e);
}

From source file:org.apache.jackrabbit.core.persistence.util.BundleWriter.java

/**
 * Write a small binary value and return the data.
 *
 * @param value the binary value//ww  w  .j a  v  a2 s . c o  m
 * @param state the property state (for error messages)
 * @param i the index (for error messages)
 * @return the data
 * @throws IOException if the data could not be read
 */
private byte[] writeSmallBinary(InternalValue value, NodePropBundle.PropertyEntry state, int i)
        throws IOException {
    try {
        int size = (int) value.getLength();
        out.writeInt(size);
        byte[] data = new byte[size];
        DataInputStream in = new DataInputStream(value.getStream());
        try {
            in.readFully(data);
        } finally {
            IOUtils.closeQuietly(in);
        }
        out.write(data, 0, data.length);
        return data;
    } catch (Exception e) {
        String msg = "Error while storing blob. id=" + state.getId() + " idx=" + i + " value=" + value;
        log.error(msg, e);
        throw new IOExceptionWithCause(msg, e);
    }
}

From source file:org.apache.jackrabbit.core.query.AbstractQueryHandler.java

public void close() throws IOException {
    if (fs != null) {
        try {//from   w ww.j  a  v  a  2s.  c  o  m
            fs.close();
        } catch (FileSystemException e) {
            throw new IOExceptionWithCause("Unable to close search index file system: " + fs, e);
        }
    }
}

From source file:org.apache.tika.parser.pdf.AbstractPDF2XHTML.java

@Override
protected void startPage(PDPage page) throws IOException {
    try {/*w w w.j a  v  a  2 s .c  om*/
        xhtml.startElement("div", "class", "page");
    } catch (SAXException e) {
        throw new IOExceptionWithCause("Unable to start a page", e);
    }
    writeParagraphStart();
}