Example usage for javax.activation MimeType MimeType

List of usage examples for javax.activation MimeType MimeType

Introduction

In this page you can find the example usage for javax.activation MimeType MimeType.

Prototype

public MimeType(String rawdata) throws MimeTypeParseException 

Source Link

Document

Constructor that builds a MimeType from a String.

Usage

From source file:net.di2e.ecdr.search.transform.atom.AbstractAtomTransformer.java

@Override
public BinaryContent transform(Metacard metacard, Map<String, Serializable> properties)
        throws CatalogTransformerException {
    if (properties == null) {
        properties = new HashMap<String, Serializable>();
    }//from   ww w  . java 2  s . c  o m
    BinaryContent binaryContent = null;
    try {
        Entry entry = getMetacardEntry(new CDRMetacard(metacard), properties);

        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        entry.writeTo(outputStream);
        binaryContent = new BinaryContentImpl(new ByteArrayInputStream(outputStream.toByteArray()),
                new MimeType(AtomResponseConstants.ATOM_MIME_TYPE));
    } catch (IOException e) {
        LOGGER.error(e.getMessage(), e);
    } catch (MimeTypeParseException e) {
        LOGGER.error(e.getMessage(), e);
    }
    return binaryContent;
}

From source file:fr.gael.dhus.datastore.processing.ProcessingManager.java

/**
 * Retrieve product indexes using its Drb node and class.
 *///from   w w w.  j  a v  a 2  s .c  om
private List<MetadataIndex> extractIndexes(DrbNode productNode, DrbCortexItemClass productClass) {
    java.util.Collection<String> properties = null;

    // Get all values of the metadata properties attached to the item
    // class or any of its super-classes
    properties = productClass.listPropertyStrings(METADATA_NAMESPACE + PROPERTY_METADATA_EXTRACTOR, false);

    // Return immediately if no property value were found
    if (properties == null) {
        LOGGER.warn("Item \"" + productClass.getLabel() + "\" has no metadata defined.");
        return null;
    }

    // Prepare the index structure.
    List<MetadataIndex> indexes = new ArrayList<MetadataIndex>();

    // Loop among retrieved property values
    for (String property : properties) {
        // Filter possible XML markup brackets that could have been encoded
        // in a CDATA section
        property = property.replaceAll("&lt;", "<");
        property = property.replaceAll("&gt;", ">");
        /*
         * property = property.replaceAll("\n", " "); // Replace eol by blank
         * space property = property.replaceAll(" +", " "); // Remove
         * contiguous blank spaces
         */

        // Create a query for the current metadata extractor
        Query metadataQuery = null;
        try {
            metadataQuery = new Query(property);
        } catch (Exception e) {
            LOGGER.error("Cannot compile metadata extractor " + "(set debug mode to see details)", e);
            if (LOGGER.isDebugEnabled()) {
                LOGGER.debug(property);
            }
            throw new RuntimeException("Cannot compile metadata extractor", e);
        }

        // Evaluate the XQuery
        DrbSequence metadataSequence = metadataQuery.evaluate(productNode);

        // Check that something results from the evaluation: jump to next
        // value otherwise
        if ((metadataSequence == null) || (metadataSequence.getLength() < 1)) {
            continue;
        }

        // Loop among results
        for (int iitem = 0; iitem < metadataSequence.getLength(); iitem++) {
            // Get current metadata node
            DrbNode n = (DrbNode) metadataSequence.getItem(iitem);

            // Get name
            DrbAttribute name_att = n.getAttribute("name");
            Value name_v = null;
            if (name_att != null)
                name_v = name_att.getValue();
            String name = null;
            if (name_v != null)
                name = name_v.convertTo(Value.STRING_ID).toString();

            // get type
            DrbAttribute type_att = n.getAttribute("type");
            Value type_v = null;
            if (type_att != null)
                type_v = type_att.getValue();
            else
                type_v = new fr.gael.drb.value.String(MIME_PLAIN_TEXT);
            String type = type_v.convertTo(Value.STRING_ID).toString();

            // get category
            DrbAttribute cat_att = n.getAttribute("category");
            Value cat_v = null;
            if (cat_att != null)
                cat_v = cat_att.getValue();
            else
                cat_v = new fr.gael.drb.value.String("product");
            String category = cat_v.convertTo(Value.STRING_ID).toString();

            // get category
            DrbAttribute qry_att = n.getAttribute("queryable");
            String queryable = null;
            if (qry_att != null) {
                Value qry_v = qry_att.getValue();
                if (qry_v != null)
                    queryable = qry_v.convertTo(Value.STRING_ID).toString();
            }

            // Get value
            String value = null;
            if (MIME_APPLICATION_GML.equals(type) && n.hasChild()) {
                ByteArrayOutputStream out = new ByteArrayOutputStream();
                XmlWriter.writeXML(n.getFirstChild(), out);
                value = out.toString();
                try {
                    out.close();
                } catch (IOException e) {
                    LOGGER.warn("Cannot close stream !", e);
                }
            } else
            // Case of "text/plain"
            {
                Value value_v = n.getValue();
                if (value_v != null) {
                    value = value_v.convertTo(Value.STRING_ID).toString();
                    value = value.trim();
                }
            }

            if ((name != null) && (value != null)) {
                MetadataIndex index = new MetadataIndex();
                index.setName(name);
                try {
                    index.setType(new MimeType(type).toString());
                } catch (MimeTypeParseException e) {
                    LOGGER.warn("Wrong metatdata extractor mime type in class \"" + productClass.getLabel()
                            + "\" for metadata called \"" + name + "\".", e);
                }
                index.setCategory(category);
                index.setValue(value);
                index.setQueryable(queryable);
                indexes.add(index);
            } else {
                String field_name = "";
                if (name != null)
                    field_name = name;
                else if (queryable != null)
                    field_name = queryable;
                else if (category != null)
                    field_name = "of category " + category;

                LOGGER.warn("Nothing extracted for field " + field_name);
            }
        }
    }
    return indexes;
}

From source file:org.codice.ddf.rest.impl.CatalogServiceImpl.java

private BinaryContent createMetacard(InputStream stream, String contentType, String transformerParam)
        throws CatalogServiceException {
    String transformer = DEFAULT_METACARD_TRANSFORMER;
    if (transformerParam != null) {
        transformer = transformerParam;/*from   w w  w.ja va2  s.  c om*/
    }

    MimeType mimeType = null;
    if (contentType != null) {
        try {
            mimeType = new MimeType(contentType);
        } catch (MimeTypeParseException e) {
            LOGGER.debug("Unable to create MimeType from raw data {}", contentType);
        }
    } else {
        LOGGER.debug("No content type specified in request");
    }

    try {
        Metacard metacard = generateMetacard(mimeType, null, stream, null);
        String metacardId = metacard.getId();
        LOGGER.debug("Metacard {} created", metacardId);
        LOGGER.debug("Transforming metacard {} to {} to be able to return it to client", metacardId,
                transformer);
        final BinaryContent content = catalogFramework.transform(metacard, transformer, null);
        LOGGER.debug("Metacard to {} transform complete for {}, preparing response.", transformer, metacardId);

        LOGGER.trace("EXITING: createMetacard");
        return content;

    } catch (MetacardCreationException | CatalogTransformerException e) {
        throw new CatalogServiceException("Unable to create metacard");
    } finally {
        try {
            if (stream != null) {
                stream.close();
            }
        } catch (IOException e) {
            LOGGER.debug("Unexpected error closing stream", e);
        }
    }
}

From source file:org.codice.ddf.endpoints.rest.RESTEndpoint.java

@POST
@Path("/metacard")
public Response createMetacard(MultipartBody multipartBody, @Context UriInfo requestUriInfo,
        @QueryParam("transform") String transformerParam) {

    LOGGER.trace("ENTERING: createMetacard");

    String contentUri = multipartBody.getAttachmentObject("contentUri", String.class);
    LOGGER.debug("contentUri = {}", contentUri);

    InputStream stream = null;/* www  . j  av a2s.c o m*/
    String filename = null;
    String contentType = null;
    Response response = null;

    String transformer = DEFAULT_METACARD_TRANSFORMER;
    if (transformerParam != null) {
        transformer = transformerParam;
    }

    Attachment contentPart = multipartBody.getAttachment(FILE_ATTACHMENT_CONTENT_ID);
    if (contentPart != null) {
        // Example Content-Type header:
        // Content-Type: application/json;id=geojson
        if (contentPart.getContentType() != null) {
            contentType = contentPart.getContentType().toString();
        }

        // Get the file contents as an InputStream and ensure the stream is positioned
        // at the beginning
        try {
            stream = contentPart.getDataHandler().getInputStream();
            if (stream != null && stream.available() == 0) {
                stream.reset();
            }
        } catch (IOException e) {
            LOGGER.warn("IOException reading stream from file attachment in multipart body", e);
        }
    } else {
        LOGGER.debug("No file contents attachment found");
    }

    MimeType mimeType = null;
    if (contentType != null) {
        try {
            mimeType = new MimeType(contentType);
        } catch (MimeTypeParseException e) {
            LOGGER.debug("Unable to create MimeType from raw data {}", contentType);
        }
    } else {
        LOGGER.debug("No content type specified in request");
    }

    try {
        Metacard metacard = generateMetacard(mimeType, "assigned-when-ingested", stream);
        String metacardId = metacard.getId();
        LOGGER.debug("Metacard {} created", metacardId);
        LOGGER.debug("Transforming metacard {} to {} to be able to return it to client", metacardId,
                transformer);
        final BinaryContent content = catalogFramework.transform(metacard, transformer, null);
        LOGGER.debug("Metacard to {} transform complete for {}, preparing response.", transformer, metacardId);

        Response.ResponseBuilder responseBuilder = Response.ok(content.getInputStream(),
                content.getMimeTypeValue());
        response = responseBuilder.build();
    } catch (MetacardCreationException | CatalogTransformerException e) {
        throw new ServerErrorException("Unable to create metacard", Status.BAD_REQUEST);
    }

    LOGGER.trace("EXITING: createMetacard");

    return response;
}

From source file:com.portfolio.rest.RestServicePortfolio.java

@Path("/portfolios/portfolio/{portfolio-id}")
@GET// w  ww  . ja  va 2s.co  m
@Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML, "application/zip",
        MediaType.APPLICATION_OCTET_STREAM })
public Object getPortfolio(@CookieParam("user") String user, @CookieParam("credential") String token,
        @QueryParam("group") int groupId, @PathParam("portfolio-id") String portfolioUuid,
        @Context ServletConfig sc, @Context HttpServletRequest httpServletRequest,
        @HeaderParam("Accept") String accept, @QueryParam("user") Integer userId,
        @QueryParam("group") Integer group, @QueryParam("resources") String resource,
        @QueryParam("files") String files, @QueryParam("export") String export,
        @QueryParam("lang") String lang) {
    UserInfo ui = checkCredential(httpServletRequest, user, token, null);

    Response response = null;
    try {
        String portfolio = dataProvider.getPortfolio(new MimeType("text/xml"), portfolioUuid, ui.userId, 0,
                this.label, resource, "", ui.subId).toString();

        if ("faux".equals(portfolio)) {
            response = Response.status(403).build();
        }

        if (response == null) {
            Date time = new Date();
            Document doc = DomUtils.xmlString2Document(portfolio, new StringBuffer());
            NodeList codes = doc.getDocumentElement().getElementsByTagName("code");
            // Le premier c'est celui du root
            Node codenode = codes.item(0);
            String code = "";
            if (codenode != null)
                code = codenode.getTextContent();

            if (export != null) {
                response = Response.ok(portfolio).header("content-disposition",
                        "attachment; filename = \"" + code + "-" + time + ".xml\"").build();
            } else if (resource != null && files != null) {
                //// Cas du renvoi d'un ZIP

                /// Temp file in temp directory
                File tempDir = new File(System.getProperty("java.io.tmpdir", null));
                File tempZip = File.createTempFile(portfolioUuid, ".zip", tempDir);

                FileOutputStream fos = new FileOutputStream(tempZip);
                ZipOutputStream zos = new ZipOutputStream(fos);
                //               BufferedOutputStream bos = new BufferedOutputStream(zos);

                /// zos.setComment("Some comment");

                /// Write xml file to zip
                ZipEntry ze = new ZipEntry(portfolioUuid + ".xml");
                zos.putNextEntry(ze);

                byte[] bytes = portfolio.getBytes("UTF-8");
                zos.write(bytes);

                zos.closeEntry();

                /// Find all fileid/filename
                XPath xPath = XPathFactory.newInstance().newXPath();
                String filterRes = "//asmResource/fileid";
                NodeList nodelist = (NodeList) xPath.compile(filterRes).evaluate(doc, XPathConstants.NODESET);

                /// Direct link to data
                // String urlTarget = "http://"+ server + "/user/" + user +"/file/" + uuid +"/"+ lang+ "/ptype/fs";

                /*
                String langatt = "";
                if( lang != null )
                   langatt = "?lang="+lang;
                else
                   langatt = "?lang=fr";
                //*/

                /// Fetch all files
                for (int i = 0; i < nodelist.getLength(); ++i) {
                    Node res = nodelist.item(i);
                    Node p = res.getParentNode(); // resource -> container
                    Node gp = p.getParentNode(); // container -> context
                    Node uuidNode = gp.getAttributes().getNamedItem("id");
                    String uuid = uuidNode.getTextContent();

                    String filterName = "./filename[@lang and text()]";
                    NodeList textList = (NodeList) xPath.compile(filterName).evaluate(p,
                            XPathConstants.NODESET);
                    String filename = "";
                    if (textList.getLength() != 0) {
                        Element fileNode = (Element) textList.item(0);
                        filename = fileNode.getTextContent();
                        lang = fileNode.getAttribute("lang");
                        if ("".equals(lang))
                            lang = "fr";
                    }

                    String servlet = httpServletRequest.getRequestURI();
                    servlet = servlet.substring(0, servlet.indexOf("/", 7));
                    String server = httpServletRequest.getServerName();
                    int port = httpServletRequest.getServerPort();
                    //                  "http://"+ server + /resources/resource/file/ uuid ? lang= size=
                    // String urlTarget = "http://"+ server + "/user/" + user +"/file/" + uuid +"/"+ lang+ "/ptype/fs";
                    String url = "http://" + server + ":" + port + servlet + "/resources/resource/file/" + uuid
                            + "?lang=" + lang;
                    HttpGet get = new HttpGet(url);

                    // Transfer sessionid so that local request still get security checked
                    HttpSession session = httpServletRequest.getSession(true);
                    get.addHeader("Cookie", "JSESSIONID=" + session.getId());

                    // Send request
                    CloseableHttpClient client = HttpClients.createDefault();
                    CloseableHttpResponse ret = client.execute(get);
                    HttpEntity entity = ret.getEntity();

                    // Put specific name for later recovery
                    if ("".equals(filename))
                        continue;
                    int lastDot = filename.lastIndexOf(".");
                    if (lastDot < 0)
                        lastDot = 0;
                    String filenameext = filename.substring(0); /// find extension
                    int extindex = filenameext.lastIndexOf(".");
                    filenameext = uuid + "_" + lang + filenameext.substring(extindex);

                    // Save it to zip file
                    //                  int length = (int) entity.getContentLength();
                    InputStream content = entity.getContent();

                    //                  BufferedInputStream bis = new BufferedInputStream(entity.getContent());

                    ze = new ZipEntry(filenameext);
                    try {
                        int totalread = 0;
                        zos.putNextEntry(ze);
                        int inByte;
                        byte[] buf = new byte[4096];
                        //                     zos.write(bytes,0,inByte);
                        while ((inByte = content.read(buf)) != -1) {
                            totalread += inByte;
                            zos.write(buf, 0, inByte);
                        }
                        System.out.println("FILE: " + filenameext + " -> " + totalread);
                        content.close();
                        //                     bis.close();
                        zos.closeEntry();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    EntityUtils.consume(entity);
                    ret.close();
                    client.close();
                }

                zos.close();
                fos.close();

                /// Return zip file
                RandomAccessFile f = new RandomAccessFile(tempZip.getAbsoluteFile(), "r");
                byte[] b = new byte[(int) f.length()];
                f.read(b);
                f.close();

                response = Response.ok(b, MediaType.APPLICATION_OCTET_STREAM)
                        .header("content-disposition", "attachment; filename = \"" + code + "-" + time + ".zip")
                        .build();

                // Temp file cleanup
                tempZip.delete();
            } else {
                //try { this.userId = userId; } catch(Exception ex) { this.userId = -1; };
                //              String returnValue = dataProvider.getPortfolio(new MimeType("text/xml"),portfolioUuid,this.userId, this.groupId, this.label, resource, files).toString();
                if (portfolio.equals("faux")) {

                    throw new RestWebApplicationException(Status.FORBIDDEN,
                            "Vous n'avez pas les droits necessaires");
                }

                if (accept.equals(MediaType.APPLICATION_JSON)) {
                    portfolio = XML.toJSONObject(portfolio).toString();
                    response = Response.ok(portfolio).type(MediaType.APPLICATION_JSON).build();
                } else
                    response = Response.ok(portfolio).type(MediaType.APPLICATION_XML).build();

                logRestRequest(httpServletRequest, null, portfolio, Status.OK.getStatusCode());
            }
        }
    } catch (RestWebApplicationException ex) {
        throw new RestWebApplicationException(Status.FORBIDDEN, ex.getResponse().getEntity().toString());
    } catch (SQLException ex) {
        logRestRequest(httpServletRequest, null, "Portfolio " + portfolioUuid + " not found",
                Status.NOT_FOUND.getStatusCode());

        throw new RestWebApplicationException(Status.NOT_FOUND, "Portfolio " + portfolioUuid + " not found");
    } catch (Exception ex) {
        ex.printStackTrace();
        logRestRequest(httpServletRequest, null, ex.getMessage() + "\n\n" + ex.getStackTrace(),
                Status.INTERNAL_SERVER_ERROR.getStatusCode());

        throw new RestWebApplicationException(Status.INTERNAL_SERVER_ERROR, ex.getMessage());
    } finally {
        if (dataProvider != null)
            dataProvider.disconnect();
    }

    return response;
}

From source file:org.codice.alliance.imaging.chip.transformer.CatalogOutputAdapter.java

private BinaryContent nitfToBinaryContent(NitfHeader header, ImageSegment imageSegment)
        throws IOException, MimeTypeParseException {
    byte[] data;/*from  w ww .j  a  v a2 s.c  om*/
    File tmpFile = File.createTempFile("nitfchip-", ".ntf");
    try {
        new NitfCreationFlowImpl().fileHeader(() -> header).imageSegment(() -> imageSegment)
                .write(tmpFile.getAbsolutePath());

        try (FileInputStream fis = new FileInputStream(tmpFile)) {
            data = IOUtils.toByteArray(fis);
        }

    } finally {
        if (!tmpFile.delete()) {
            LOGGER.debug("unable to delete the temporary file '{}'", tmpFile);
        }
    }

    return new BinaryContentImpl(new ByteArrayInputStream(data), new MimeType(IMAGE_NITF));
}

From source file:org.opensextant.xtext.XText.java

/**
 * Save children objects for a given ConvertedDocument to a location....
 * convert those items immediately, saving the Parent metadata along with
 * them. You should have setParent already
 *
 * @param parentDoc/*  w ww .  j  a va  2s.co  m*/
 *            parent conversion
 * @throws IOException
 *             on err
 */
public void convertChildren(ConvertedDocument parentDoc) throws IOException {

    if (parentDoc.is_webArchive) {
        // Web Archive is a single document.  Only intent here is to convert to a single text document.
        //
        return;
    }

    parentDoc.evalParentChildContainer();
    FileUtility.makeDirectory(parentDoc.parentContainer);
    String targetPath = parentDoc.parentContainer.getAbsolutePath();

    for (Content child : parentDoc.getRawChildren()) {
        if (child.content == null) {
            log.error("Attempted to write out child object with no content {}", child.id);
            continue;
        }

        OutputStream io = null;
        try {
            // We just assume for now Child ID is filename.
            // Alternatively, child.meta.getProperty(
            // ConvertedDocument.CHILD_ENTRY_KEY )
            // same result, just more verbose.
            //
            File childFile = new File(FilenameUtils.concat(targetPath, child.id));
            io = new FileOutputStream(childFile);
            IOUtils.write(child.content, io);

            ConvertedDocument childConv = convertFile(childFile, parentDoc);
            if (childConv != null) {
                if (childConv.is_converted) {
                    // Push down all child metadata down to ConvertedDoc
                    for (String k : child.meta.stringPropertyNames()) {
                        String val = child.meta.getProperty(k);
                        childConv.addUserProperty(k, val);
                    }
                    // Save cached version once again.
                    childConv.saveBuffer(new File(childConv.textpath));
                }

                if (child.mimeType != null) {
                    try {
                        childConv.setMimeType(new MimeType(child.mimeType));
                    } catch (MimeTypeParseException e) {
                        log.warn("Invalid mime type encountered: {} ignoring.", child.mimeType);
                    }
                }

                parentDoc.addChild(childConv);
            }
        } catch (Exception err) {
            log.error("Failed to write out child {}, but will continue with others", child.id, err);
        } finally {
            if (io != null) {
                io.close();
            }
        }
    }
}

From source file:ddf.catalog.resource.download.ReliableResourceDownloadManagerTest.java

private ResourceResponse getMockResourceResponse() throws Exception {
    resourceRequest = mock(ResourceRequest.class);
    Map<String, Serializable> requestProperties = new HashMap<String, Serializable>();
    when(resourceRequest.getPropertyNames()).thenReturn(requestProperties.keySet());

    resource = mock(Resource.class);
    when(resource.getInputStream()).thenReturn(mis);
    when(resource.getName()).thenReturn("test-resource");
    when(resource.getMimeType()).thenReturn(new MimeType("text/plain"));

    resourceResponse = mock(ResourceResponse.class);
    when(resourceResponse.getRequest()).thenReturn(resourceRequest);
    when(resourceResponse.getResource()).thenReturn(resource);
    Map<String, Serializable> responseProperties = new HashMap<String, Serializable>();
    when(resourceResponse.getProperties()).thenReturn(responseProperties);

    return resourceResponse;
}

From source file:ddf.catalog.impl.CatalogFrameworkImpl.java

private Metacard generateMetacard(String mimeTypeRaw, String id, String fileName, long size, Subject subject,
        Path tmpContentPath) throws MetacardCreationException, MimeTypeParseException {

    Metacard generatedMetacard = null;/*  ww  w. j a  va  2 s  .  c om*/
    InputTransformer transformer = null;
    StringBuilder causeMessage = new StringBuilder("Could not create metacard with mimeType ");
    try {
        MimeType mimeType = new MimeType(mimeTypeRaw);

        List<InputTransformer> listOfCandidates = frameworkProperties.getMimeTypeToTransformerMapper()
                .findMatches(InputTransformer.class, mimeType);

        LOGGER.debug("List of matches for mimeType [{}]: {}", mimeType, listOfCandidates);

        for (InputTransformer candidate : listOfCandidates) {
            transformer = candidate;

            try (InputStream transformerStream = com.google.common.io.Files
                    .asByteSource(tmpContentPath.toFile()).openStream()) {
                generatedMetacard = transformer.transform(transformerStream);
            }
            if (generatedMetacard != null) {
                break;
            }
        }
    } catch (CatalogTransformerException | IOException e) {
        causeMessage.append(mimeTypeRaw).append(". Reason: ").append(System.lineSeparator())
                .append(e.getMessage());

        // The caught exception more than likely does not have the root cause message
        // that is needed to inform the caller as to why things have failed.  Therefore
        // we need to iterate through the chain of cause exceptions and gather up
        // all of their message details.
        Throwable cause = e.getCause();
        while (cause != null && cause != cause.getCause()) {
            causeMessage.append(System.lineSeparator()).append(cause.getMessage());
            cause = cause.getCause();
        }
        LOGGER.debug("Transformer [{}] could not create metacard.", transformer, e);
    }

    if (generatedMetacard == null) {
        throw new MetacardCreationException(causeMessage.toString());
    }

    if (id != null) {
        generatedMetacard.setAttribute(new AttributeImpl(Metacard.ID, id));
    } else {
        generatedMetacard
                .setAttribute(new AttributeImpl(Metacard.ID, UUID.randomUUID().toString().replaceAll("-", "")));
    }

    if (StringUtils.isBlank(generatedMetacard.getTitle())) {
        generatedMetacard.setAttribute(new AttributeImpl(Metacard.TITLE, fileName));
    }

    String name = SubjectUtils.getName(subject);

    generatedMetacard.setAttribute(new AttributeImpl(Metacard.POINT_OF_CONTACT, name == null ? "" : name));

    return generatedMetacard;

}

From source file:ddf.catalog.resource.download.ReliableResourceDownloadManagerTest.java

private ResourceRetriever getMockResourceRetrieverWithRetryCapability(final RetryType retryType,
        final boolean readSlow) throws Exception {

    // Mocking to support re-retrieval of product when error encountered
    // during caching.
    ResourceRetriever retriever = mock(ResourceRetriever.class);
    when(retriever.retrieveResource()).thenAnswer(new Answer<Object>() {
        int invocationCount = 0;

        public Object answer(InvocationOnMock invocation) throws ResourceNotFoundException {
            // Create new InputStream for retrieving the same product. This
            // simulates re-retrieving the product from the remote source.
            invocationCount++;/*from  w ww .java  2  s .c  o m*/
            if (readSlow) {
                mis = new MockInputStream(productInputFilename, true);
                mis.setReadDelay(MONITOR_PERIOD - 2, TimeUnit.MILLISECONDS);
            } else {
                mis = new MockInputStream(productInputFilename);
            }

            if (retryType == RetryType.INPUT_STREAM_IO_EXCEPTION) {
                if (invocationCount == 1) {
                    mis.setInvocationCountToThrowIOException(5);
                } else {
                    mis.setInvocationCountToThrowIOException(-1);
                }
            } else if (retryType == RetryType.TIMEOUT_EXCEPTION) {
                if (invocationCount == 1) {
                    mis.setInvocationCountToTimeout(3);
                    mis.setReadDelay(MONITOR_PERIOD * 2, TimeUnit.SECONDS);
                } else {
                    mis.setInvocationCountToTimeout(-1);
                    mis.setReadDelay(0, TimeUnit.SECONDS);
                }
            } else if (retryType == RetryType.NETWORK_CONNECTION_UP_AND_DOWN) {
                mis.setInvocationCountToThrowIOException(2);
            } else if (retryType == RetryType.NETWORK_CONNECTION_DROPPED) {
                if (invocationCount == 1) {
                    mis.setInvocationCountToThrowIOException(2);
                } else {
                    throw new ResourceNotFoundException();
                }
            }

            // Reset the mock Resource so that it can be reconfigured to return
            // the new InputStream
            reset(resource);
            when(resource.getInputStream()).thenReturn(mis);
            when(resource.getName()).thenReturn("test-resource");
            try {
                when(resource.getMimeType()).thenReturn(new MimeType("text/plain"));
            } catch (MimeTypeParseException e) {
            }

            // Reset the mock ResourceResponse so that it can be reconfigured to return
            // the new Resource
            reset(resourceResponse);
            when(resourceResponse.getRequest()).thenReturn(resourceRequest);
            when(resourceResponse.getResource()).thenReturn(resource);
            when(resourceResponse.getProperties()).thenReturn(new HashMap<String, Serializable>());

            return resourceResponse;
        }
    });

    ArgumentCaptor<Long> bytesReadArg = ArgumentCaptor.forClass(Long.class);

    // Mocking to support re-retrieval of product when error encountered
    // during caching. This resource retriever supports skipping.
    when(retriever.retrieveResource(anyLong())).thenAnswer(new Answer<Object>() {
        int invocationCount = 0;

        public Object answer(InvocationOnMock invocation) throws ResourceNotFoundException, IOException {
            // Create new InputStream for retrieving the same product. This
            // simulates re-retrieving the product from the remote source.
            invocationCount++;
            if (readSlow) {
                mis = new MockInputStream(productInputFilename, true);
                mis.setReadDelay(MONITOR_PERIOD - 2, TimeUnit.MILLISECONDS);
            } else {
                mis = new MockInputStream(productInputFilename);
            }

            // Skip the number of bytes that have already been read
            Object[] args = invocation.getArguments();
            long bytesToSkip = (Long) args[0];

            mis.skip(bytesToSkip);

            if (retryType == RetryType.INPUT_STREAM_IO_EXCEPTION) {
                if (invocationCount == 1) {
                    mis.setInvocationCountToThrowIOException(5);
                } else {
                    mis.setInvocationCountToThrowIOException(-1);
                }
            } else if (retryType == RetryType.TIMEOUT_EXCEPTION) {
                if (invocationCount == 1) {
                    mis.setInvocationCountToTimeout(3);
                    mis.setReadDelay(MONITOR_PERIOD * 2, TimeUnit.SECONDS);
                } else {
                    mis.setInvocationCountToTimeout(-1);
                    mis.setReadDelay(0, TimeUnit.MILLISECONDS);
                }
            } else if (retryType == RetryType.NETWORK_CONNECTION_UP_AND_DOWN) {
                mis.setInvocationCountToThrowIOException(2);
            } else if (retryType == RetryType.NETWORK_CONNECTION_DROPPED) {
                if (invocationCount == 1) {
                    mis.setInvocationCountToThrowIOException(2);
                } else {
                    throw new ResourceNotFoundException();
                }
            }

            // Reset the mock Resource so that it can be reconfigured to return
            // the new InputStream
            reset(resource);
            when(resource.getInputStream()).thenReturn(mis);
            when(resource.getName()).thenReturn("test-resource");
            try {
                when(resource.getMimeType()).thenReturn(new MimeType("text/plain"));
            } catch (MimeTypeParseException e) {
            }

            // Reset the mock ResourceResponse so that it can be reconfigured to return
            // the new Resource
            reset(resourceResponse);
            when(resourceResponse.getRequest()).thenReturn(resourceRequest);
            when(resourceResponse.getResource()).thenReturn(resource);
            Map<String, Serializable> responseProperties = new HashMap<>();
            responseProperties.put("BytesSkipped", true);
            when(resourceResponse.getProperties()).thenReturn(responseProperties);
            when(resourceResponse.containsPropertyName("BytesSkipped")).thenReturn(true);
            when(resourceResponse.getPropertyValue("BytesSkipped")).thenReturn(true);

            return resourceResponse;
        }
    });

    return retriever;
}