Example usage for org.apache.http.message BasicHeaderValueParser BasicHeaderValueParser

List of usage examples for org.apache.http.message BasicHeaderValueParser BasicHeaderValueParser

Introduction

In this page you can find the example usage for org.apache.http.message BasicHeaderValueParser BasicHeaderValueParser.

Prototype

BasicHeaderValueParser

Source Link

Usage

From source file:com.google.android.feeds.ContentHandlerUtils.java

/**
 * Returns the character set of the content provided by the given
 * {@link URLConnection}.//from   w  w  w  . j  av a 2  s.c o  m
 *
 * @throws IOException if the character set cannot be determined.
 */
public static String getCharSet(URLConnection connection) throws IOException {
    String contentType = connection.getContentType();
    if (contentType != null) {
        HeaderValueParser parser = new BasicHeaderValueParser();
        HeaderElement[] values = BasicHeaderValueParser.parseElements(contentType, parser);
        if (values.length > 0) {
            NameValuePair param = values[0].getParameterByName("charset");
            if (param != null) {
                return param.getValue();
            }
        }
    }
    if (connection instanceof HttpURLConnection) {
        return HTTP.DEFAULT_CONTENT_CHARSET;
    } else {
        throw new IOException("Unabled to determine character encoding");
    }
}

From source file:org.expath.servlex.functions.ParseHeaderValueCallTest.java

@Test
public void reproduceTheAlgorithm() {
    String value = "attachment; filename=\"fname.ext\"";
    HeaderValueParser parser = new BasicHeaderValueParser();
    HeaderElement[] elems = BasicHeaderValueParser.parseElements(value, parser);
    for (HeaderElement e : elems) {
        System.err.println("element: " + e.getName());
        if (e.getValue() != null) {
            System.err.println("   : " + e.getValue());
        }//from  w  ww . j  a v  a 2  s  .c  om
        for (NameValuePair p : e.getParameters()) {
            System.err.println("  param: " + p.getName());
            if (p.getValue() != null) {
                System.err.println("     : " + p.getValue());
            }
        }
    }
}

From source file:org.expath.servlex.tools.ContentType.java

private void init(String value) throws TechnicalException {
    LOG.debug("Content type - original : " + value);
    myOriginal = value;/*from w ww . jav  a2  s .  c  om*/
    HeaderValueParser parser = new BasicHeaderValueParser();
    HeaderElement[] elems = BasicHeaderValueParser.parseElements(value, parser);
    if (elems.length != 1) {
        String msg = "Content-Type does not have exactly one element, it has ";
        throw new TechnicalException(msg + elems.length + " (" + value + ")");
    }
    String type = elems[0].getName();
    int slash = type.indexOf('/');
    if (slash <= 0) {
        String msg = "Content-Type does not contain any slash character (" + value + ")";
        throw new TechnicalException(msg);
    }
    myMainType = type.substring(0, slash);
    mySubType = type.substring(slash + 1);
    NameValuePair param = elems[0].getParameterByName("charset");
    if (param != null) {
        myCharset = param.getValue();
    }
    LOG.debug("Content type - main type: " + myMainType);
    LOG.debug("Content type - sub type : " + mySubType);
    LOG.debug("Content type - charset  : " + myCharset);
}

From source file:org.opendatakit.odktables.InstanceFileManager.java

public void postFiles(String tableId, String rowId, MultiPart multiPart, TablesUserPermissions userPermissions)
        throws IOException, ODKTaskLockException, ODKTablesException, ODKDatastoreException {

    try {//from w  w w .j  a  va  2 s  . c om
        if (tableId == null) {
            throw new IllegalArgumentException("tableId cannot be null!");
        }

        if (rowId == null) {
            throw new IllegalArgumentException("rowId cannot be null!");
        }

        userPermissions.checkPermission(appId, tableId, TablePermission.WRITE_ROW);

        OdkTablesLockTemplate propsLock = new OdkTablesLockTemplate(tableId, rowId,
                ODKTablesTaskLockType.TABLES_NON_PERMISSIONS_CHANGES, OdkTablesLockTemplate.DelayStrategy.LONG,
                cc);

        try {
            propsLock.acquire();

            // fetch these once and then continue to re-use them.
            DbTableInstanceFiles blobStore = new DbTableInstanceFiles(tableId, cc);
            BlobEntitySet instance = blobStore.newBlobEntitySet(rowId, cc);

            ODKTablesException e = null;
            // Parse the request
            for (BodyPart bodyPart : multiPart.getBodyParts()) {

                MultivaluedMap<String, String> headers = bodyPart.getHeaders();
                String disposition = (headers != null) ? headers.getFirst("Content-Disposition") : null;
                if (disposition == null) {
                    e = new ODKTablesException(InstanceFileService.ERROR_MSG_MULTIPART_FILES_ONLY_EXPECTED);
                    continue;
                }
                String partialPath = null;
                {
                    HeaderValueParser parser = new BasicHeaderValueParser();
                    HeaderElement[] values = BasicHeaderValueParser.parseElements(disposition, parser);
                    for (HeaderElement v : values) {
                        if (v.getName().equalsIgnoreCase("file")) {
                            partialPath = v.getParameterByName("filename").getValue();
                            break;
                        }
                    }
                }
                if (partialPath == null) {
                    e = new ODKTablesException(
                            InstanceFileService.ERROR_MSG_MULTIPART_CONTENT_FILENAME_EXPECTED);
                    continue;
                }

                String contentType = (headers != null) ? headers.getFirst("Content-Type") : null;

                ByteArrayOutputStream bo = new ByteArrayOutputStream();
                InputStream bi = null;
                BodyPartEntity bodyPartEntity = (BodyPartEntity) bodyPart.getEntity();
                try {
                    bi = new BufferedInputStream(bodyPartEntity.getInputStream());
                    int length = 1024;
                    // Transfer bytes from in to out
                    byte[] data = new byte[length];
                    int len;
                    while ((len = bi.read(data, 0, length)) >= 0) {
                        if (len != 0) {
                            bo.write(data, 0, len);
                        }
                    }
                } finally {
                    bi.close();
                }
                byte[] content = bo.toByteArray();
                String md5Hash = PersistenceUtils.newMD5HashUri(content);

                // we are adding one or more files -- delete any cached ETag value for
                // this row's attachments manifest
                try {
                    DbTableInstanceManifestETagEntity entity = DbTableInstanceManifestETags
                            .getRowIdEntry(tableId, rowId, cc);
                    entity.delete(cc);
                } catch (ODKEntityNotFoundException ex) {
                    // ignore... it might already be deleted or have never existed
                }

                int count = instance.getAttachmentCount(cc);
                boolean found = false;
                for (int i = 1; i <= count; ++i) {
                    String path = instance.getUnrootedFilename(i, cc);
                    if (path != null && path.equals(partialPath)) {
                        // we already have this in our store -- check that it is
                        // identical.
                        // if not, we have a problem!!!
                        if (md5Hash.equals(instance.getContentHash(i, cc))) {
                            // no-op
                            found = true;
                        } else {
                            // this is an error case; indicated by setting exception
                            found = true;
                            e = new InstanceFileModificationException(
                                    ERROR_FILE_VERSION_DIFFERS + "\n" + partialPath);
                            break;
                        }
                    }
                }
                if (!found) {
                    BlobSubmissionOutcome outcome = instance.addBlob(content, contentType, partialPath, false,
                            cc);
                    if (outcome == BlobSubmissionOutcome.NEW_FILE_VERSION) {
                        e = new InstanceFileModificationException(
                                ERROR_FILE_VERSION_DIFFERS + "\n" + partialPath);
                    }
                }
            }
            if (e != null) {
                throw e;
            }
        } finally {
            propsLock.release();
        }
    } catch (NullPointerException e) {
        e.printStackTrace();
        throw e;
    } catch (IllegalArgumentException e) {
        e.printStackTrace();
        throw e;
    } catch (IndexOutOfBoundsException e) {
        e.printStackTrace();
        throw e;
    } catch (ODKTaskLockException e) {
        e.printStackTrace();
        throw e;
    } catch (PermissionDeniedException e) {
        e.printStackTrace();
        throw e;
    } catch (ODKDatastoreException e) {
        e.printStackTrace();
        throw e;
    }
}

From source file:org.opendatakit.aggregate.odktables.InstanceFileManager.java

public void postFiles(String tableId, String rowId, InMultiPart inMP, TablesUserPermissions userPermissions)
        throws IOException, ODKTaskLockException, ODKTablesException, ODKDatastoreException {

    try {//from  www.  j  a v  a2  s.c  om
        if (tableId == null) {
            throw new IllegalArgumentException("tableId cannot be null!");
        }

        if (rowId == null) {
            throw new IllegalArgumentException("rowId cannot be null!");
        }

        userPermissions.checkPermission(appId, tableId, TablePermission.WRITE_ROW);

        OdkTablesLockTemplate propsLock = new OdkTablesLockTemplate(tableId, rowId,
                ODKTablesTaskLockType.TABLES_NON_PERMISSIONS_CHANGES, OdkTablesLockTemplate.DelayStrategy.LONG,
                cc);

        try {
            propsLock.acquire();

            // fetch these once and then continue to re-use them.
            DbTableInstanceFiles blobStore = new DbTableInstanceFiles(tableId, cc);
            BlobEntitySet instance = blobStore.newBlobEntitySet(rowId, cc);

            ODKTablesException e = null;
            // Parse the request
            while (inMP.hasNext()) {
                InPart part = inMP.next();
                MultivaluedMap<String, String> headers = part.getHeaders();
                String disposition = (headers != null) ? headers.getFirst("Content-Disposition") : null;
                if (disposition == null) {
                    e = new ODKTablesException(InstanceFileService.ERROR_MSG_MULTIPART_FILES_ONLY_EXPECTED);
                    continue;
                }
                String partialPath = null;
                {
                    HeaderValueParser parser = new BasicHeaderValueParser();
                    HeaderElement[] values = BasicHeaderValueParser.parseElements(disposition, parser);
                    for (HeaderElement v : values) {
                        if (v.getName().equalsIgnoreCase("file")) {
                            partialPath = v.getParameterByName("filename").getValue();
                            break;
                        }
                    }
                }
                if (partialPath == null) {
                    e = new ODKTablesException(
                            InstanceFileService.ERROR_MSG_MULTIPART_CONTENT_FILENAME_EXPECTED);
                    continue;
                }

                String contentType = (headers != null) ? headers.getFirst("Content-Type") : null;

                ByteArrayOutputStream bo = new ByteArrayOutputStream();
                InputStream bi = null;
                try {
                    bi = new BufferedInputStream(part.getInputStream());
                    int length = 1024;
                    // Transfer bytes from in to out
                    byte[] data = new byte[length];
                    int len;
                    while ((len = bi.read(data, 0, length)) >= 0) {
                        if (len != 0) {
                            bo.write(data, 0, len);
                        }
                    }
                } finally {
                    bi.close();
                }
                byte[] content = bo.toByteArray();
                String md5Hash = PersistenceUtils.newMD5HashUri(content);

                // we are adding one or more files -- delete any cached ETag value for
                // this row's attachments manifest
                try {
                    DbTableInstanceManifestETagEntity entity = DbTableInstanceManifestETags
                            .getRowIdEntry(tableId, rowId, cc);
                    entity.delete(cc);
                } catch (ODKEntityNotFoundException ex) {
                    // ignore... it might already be deleted or have never existed
                }

                int count = instance.getAttachmentCount(cc);
                boolean found = false;
                for (int i = 1; i <= count; ++i) {
                    String path = instance.getUnrootedFilename(i, cc);
                    if (path != null && path.equals(partialPath)) {
                        // we already have this in our store -- check that it is
                        // identical.
                        // if not, we have a problem!!!
                        if (md5Hash.equals(instance.getContentHash(i, cc))) {
                            // no-op
                            found = true;
                        } else {
                            // this is an error case; indicated by setting exception
                            found = true;
                            e = new InstanceFileModificationException(
                                    ERROR_FILE_VERSION_DIFFERS + "\n" + partialPath);
                            break;
                        }
                    }
                }
                if (!found) {
                    BlobSubmissionOutcome outcome = instance.addBlob(content, contentType, partialPath, false,
                            cc);
                    if (outcome == BlobSubmissionOutcome.NEW_FILE_VERSION) {
                        e = new InstanceFileModificationException(
                                ERROR_FILE_VERSION_DIFFERS + "\n" + partialPath);
                    }
                }
            }
            if (e != null) {
                throw e;
            }
        } finally {
            propsLock.release();
        }
    } catch (NullPointerException e) {
        e.printStackTrace();
        throw e;
    } catch (IllegalArgumentException e) {
        e.printStackTrace();
        throw e;
    } catch (IndexOutOfBoundsException e) {
        e.printStackTrace();
        throw e;
    } catch (ODKTaskLockException e) {
        e.printStackTrace();
        throw e;
    } catch (PermissionDeniedException e) {
        e.printStackTrace();
        throw e;
    } catch (ODKDatastoreException e) {
        e.printStackTrace();
        throw e;
    }
}