List of usage examples for javax.activation MimeType MimeType
public MimeType(String rawdata) throws MimeTypeParseException
From source file:org.codice.ddf.catalog.ui.metacard.ListApplication.java
private List<Splitter> lookupSplitters(String mimeType) throws MimeTypeParseException { List<Splitter> splitters = splitterLocator.find(new MimeType(mimeType)); if (CollectionUtils.isEmpty(splitters)) { LOGGER.debug("Unable to find a splitter for mime-type {}", mimeType); }//from w w w.ja v a 2 s . co m return splitters; }
From source file:eu.fusepool.p3.proxy.ProxyHandler.java
private void startTransformation(final String resourceUri, final String ldpcUri, final String transformerUri, final byte[] bytes, final Header[] requestHeaders) { (new Thread() { @Override/*from w w w . j a v a2 s . c o m*/ public void run() { Transformer transformer = new TransformerClientImpl(transformerUri); Entity entity = new InputStreamEntity() { @Override public MimeType getType() { try { for (Header h : requestHeaders) { if (h.getName().equalsIgnoreCase("Content-Type")) { return new MimeType(h.getValue()); } } return new MimeType("application/octet-stream"); } catch (MimeTypeParseException ex) { throw new RuntimeException(ex); } } @Override public InputStream getData() throws IOException { return new ByteArrayInputStream(bytes); } @Override public URI getContentLocation() { try { return new URI(resourceUri); } catch (URISyntaxException ex) { throw new RuntimeException(ex); } } }; Entity transformationResult; try { transformationResult = transformer.transform(entity, new MimeType("*/*")); } catch (MimeTypeParseException ex) { throw new RuntimeException(ex); } //final HttpEntity httpEntity = response.getEntity(); //final Header contentTypeHeader = httpEntity.getContentType(); final String contentType = transformationResult.getType().toString(); try { if (isRdf(contentType)) { Graph transformationResultGraph = parser.parse(transformationResult.getData(), contentType); final ByteArrayOutputStream baos = new ByteArrayOutputStream(); serializer.serialize(baos, transformationResultGraph, SupportedFormat.TURTLE); final byte[] bytes = baos.toByteArray(); final StringWriter turtleString = new StringWriter(baos.size() + 2000); turtleString.append(new String(bytes, "UTF-8")); turtleString.append('\n'); turtleString.append("<> " + ELDP.transformedFrom + " <" + resourceUri + "> ."); post(ldpcUri, new ByteArrayEntity(turtleString.toString().getBytes("UTF-8")), "text/turtle", resourceUri, requestHeaders); } else { post(ldpcUri, new org.apache.http.entity.InputStreamEntity(transformationResult.getData()), contentType, resourceUri, requestHeaders); } } catch (IOException ex) { throw new RuntimeException(ex); } } }).start(); }
From source file:com.portfolio.data.attachment.XSLService.java
@Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException { /**/*from ww w .j av a 2 s .c o m*/ * Format demand: * <convert> * <portfolioid>{uuid}</portfolioid> * <portfolioid>{uuid}</portfolioid> * <nodeid>{uuid}</nodeid> * <nodeid>{uuid}</nodeid> * <documentid>{uuid}</documentid> * <xsl>{rpertoire}{fichier}</xsl> * <format>[pdf rtf xml ...]</format> * <parameters> * <maVar1>lala</maVar1> * ... * </parameters> * </convert> */ try { //On initialise le dataProvider Connection c = null; //On initialise le dataProvider if (ds == null) // Case where we can't deploy context.xml { c = getConnection(); } else { c = ds.getConnection(); } dataProvider.setConnection(c); credential = new Credential(c); } catch (Exception e) { e.printStackTrace(); } String origin = request.getRequestURL().toString(); /// Variable stuff int userId = 0; int groupId = 0; String user = ""; HttpSession session = request.getSession(true); if (session != null) { Integer val = (Integer) session.getAttribute("uid"); if (val != null) userId = val; val = (Integer) session.getAttribute("gid"); if (val != null) groupId = val; user = (String) session.getAttribute("user"); } /// TODO: A voire si un form get ne ferait pas l'affaire aussi /// On lis le xml /* BufferedReader rd = new BufferedReader(new InputStreamReader(request.getInputStream())); StringBuilder sb = new StringBuilder(); String line; while( (line = rd.readLine()) != null ) sb.append(line); DocumentBuilderFactory documentBuilderFactory =DocumentBuilderFactory.newInstance(); DocumentBuilder documentBuilder = null; Document doc=null; try { documentBuilder = documentBuilderFactory.newDocumentBuilder(); doc = documentBuilder.parse(new ByteArrayInputStream(sb.toString().getBytes("UTF-8"))); } catch( Exception e ) { e.printStackTrace(); } /// On lit les paramtres NodeList portfolioNode = doc.getElementsByTagName("portfolioid"); NodeList nodeNode = doc.getElementsByTagName("nodeid"); NodeList documentNode = doc.getElementsByTagName("documentid"); NodeList xslNode = doc.getElementsByTagName("xsl"); NodeList formatNode = doc.getElementsByTagName("format"); NodeList parametersNode = doc.getElementsByTagName("parameters"); //*/ // String xslfile = xslNode.item(0).getTextContent(); String xslfile = request.getParameter("xsl"); String format = request.getParameter("format"); // String format = formatNode.item(0).getTextContent(); String parameters = request.getParameter("parameters"); String documentid = request.getParameter("documentid"); String portfolios = request.getParameter("portfolioids"); String[] portfolioid = null; if (portfolios != null) portfolioid = portfolios.split(";"); String nodes = request.getParameter("nodeids"); String[] nodeid = null; if (nodes != null) nodeid = nodes.split(";"); System.out.println("PARAMETERS: "); System.out.println("xsl: " + xslfile); System.out.println("format: " + format); System.out.println("user: " + userId); System.out.println("portfolioids: " + portfolios); System.out.println("nodeids: " + nodes); System.out.println("parameters: " + parameters); boolean redirectDoc = false; if (documentid != null) { redirectDoc = true; System.out.println("documentid @ " + documentid); } boolean usefop = false; String ext = ""; if (MimeConstants.MIME_PDF.equals(format)) { usefop = true; ext = ".pdf"; } else if (MimeConstants.MIME_RTF.equals(format)) { usefop = true; ext = ".rtf"; } //// Paramtre portfolio-uuid et file-xsl // String uuid = request.getParameter("uuid"); // String xslfile = request.getParameter("xsl"); StringBuilder aggregate = new StringBuilder(); try { int portcount = 0; int nodecount = 0; // On aggrge les donnes if (portfolioid != null) { portcount = portfolioid.length; for (int i = 0; i < portfolioid.length; ++i) { String p = portfolioid[i]; String portfolioxml = dataProvider .getPortfolio(new MimeType("text/xml"), p, userId, groupId, "", null, null, 0) .toString(); aggregate.append(portfolioxml); } } if (nodeid != null) { nodecount = nodeid.length; for (int i = 0; i < nodeid.length; ++i) { String n = nodeid[i]; String nodexml = dataProvider.getNode(new MimeType("text/xml"), n, true, userId, groupId, "") .toString(); aggregate.append(nodexml); } } // Est-ce qu'on a eu besoin d'aggrger les donnes? String input = aggregate.toString(); String pattern = "<\\?xml[^>]*>"; // Purge previous xml declaration input = input.replaceAll(pattern, ""); input = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + "<!DOCTYPE xsl:stylesheet [" + "<!ENTITY % lat1 PUBLIC \"-//W3C//ENTITIES Latin 1 for XHTML//EN\" \"" + servletDir + "xhtml-lat1.ent\">" + "<!ENTITY % symbol PUBLIC \"-//W3C//ENTITIES Symbols for XHTML//EN\" \"" + servletDir + "xhtml-symbol.ent\">" + "<!ENTITY % special PUBLIC \"-//W3C//ENTITIES Special for XHTML//EN\" \"" + servletDir + "xhtml-special.ent\">" + "%lat1;" + "%symbol;" + "%special;" + "]>" + // For the pesky special characters "<root>" + input + "</root>"; // System.out.println("INPUT WITH PROXY:"+ input); /// Rsolution des proxys DocumentBuilder documentBuilder; DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); documentBuilder = documentBuilderFactory.newDocumentBuilder(); InputSource is = new InputSource(new StringReader(input)); Document doc = documentBuilder.parse(is); /// Proxy stuff XPath xPath = XPathFactory.newInstance().newXPath(); String filterRes = "//asmResource[@xsi_type='Proxy']"; String filterCode = "./code/text()"; NodeList nodelist = (NodeList) xPath.compile(filterRes).evaluate(doc, XPathConstants.NODESET); XPathExpression codeFilter = xPath.compile(filterCode); for (int i = 0; i < nodelist.getLength(); ++i) { Node res = nodelist.item(i); Node gp = res.getParentNode(); // resource -> context -> container Node ggp = gp.getParentNode(); Node uuid = (Node) codeFilter.evaluate(res, XPathConstants.NODE); /// Fetch node we want to replace String returnValue = dataProvider .getNode(new MimeType("text/xml"), uuid.getTextContent(), true, userId, groupId, "") .toString(); Document rep = documentBuilder.parse(new InputSource(new StringReader(returnValue))); Element repNode = rep.getDocumentElement(); Node proxyNode = repNode.getFirstChild(); proxyNode = doc.importNode(proxyNode, true); // adoptNode have some weird side effect. To be banned // doc.replaceChild(proxyNode, gp); ggp.insertBefore(proxyNode, gp); // replaceChild doesn't work. ggp.removeChild(gp); } try // Convert XML document to string { DOMSource domSource = new DOMSource(doc); StringWriter writer = new StringWriter(); StreamResult result = new StreamResult(writer); TransformerFactory tf = TransformerFactory.newInstance(); Transformer transformer = tf.newTransformer(); transformer.transform(domSource, result); writer.flush(); input = writer.toString(); } catch (TransformerException ex) { ex.printStackTrace(); } // System.out.println("INPUT DATA:"+ input); // Setup a buffer to obtain the content length ByteArrayOutputStream stageout = new ByteArrayOutputStream(); ByteArrayOutputStream out = new ByteArrayOutputStream(); //// Setup Transformer (1st stage) /// Base path String basepath = xslfile.substring(0, xslfile.indexOf(File.separator)); String firstStage = baseDir + File.separator + basepath + File.separator + "karuta" + File.separator + "xsl" + File.separator + "html2xml.xsl"; System.out.println("FIRST: " + firstStage); Source xsltSrc1 = new StreamSource(new File(firstStage)); Transformer transformer1 = transFactory.newTransformer(xsltSrc1); StreamSource stageSource = new StreamSource(new ByteArrayInputStream(input.getBytes())); Result stageRes = new StreamResult(stageout); transformer1.transform(stageSource, stageRes); // Setup Transformer (2nd stage) String secondStage = baseDir + File.separator + xslfile; Source xsltSrc2 = new StreamSource(new File(secondStage)); Transformer transformer2 = transFactory.newTransformer(xsltSrc2); // Configure parameter from xml String[] table = parameters.split(";"); for (int i = 0; i < table.length; ++i) { String line = table[i]; int var = line.indexOf(":"); String par = line.substring(0, var); String val = line.substring(var + 1); transformer2.setParameter(par, val); } // Setup input StreamSource xmlSource = new StreamSource(new ByteArrayInputStream(stageout.toString().getBytes())); // StreamSource xmlSource = new StreamSource(new File(baseDir+origin, "projectteam.xml") ); Result res = null; if (usefop) { /// FIXME: Might need to include the entity for html stuff? //Setup FOP //Make sure the XSL transformation's result is piped through to FOP Fop fop = fopFactory.newFop(format, out); res = new SAXResult(fop.getDefaultHandler()); //Start the transformation and rendering process transformer2.transform(xmlSource, res); } else { res = new StreamResult(out); //Start the transformation and rendering process transformer2.transform(xmlSource, res); } if (redirectDoc) { // /resources/resource/file/{uuid}[?size=[S|L]&lang=[fr|en]] String urlTarget = "http://" + server + "/resources/resource/file/" + documentid; System.out.println("Redirect @ " + urlTarget); HttpClientBuilder clientbuilder = HttpClientBuilder.create(); CloseableHttpClient client = clientbuilder.build(); HttpPost post = new HttpPost(urlTarget); post.addHeader("referer", origin); String sessionid = request.getSession().getId(); System.out.println("Session: " + sessionid); post.addHeader("Cookie", "JSESSIONID=" + sessionid); MultipartEntityBuilder builder = MultipartEntityBuilder.create(); builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); ByteArrayBody body = new ByteArrayBody(out.toByteArray(), "generated" + ext); builder.addPart("uploadfile", body); HttpEntity entity = builder.build(); post.setEntity(entity); HttpResponse ret = client.execute(post); String stringret = new BasicResponseHandler().handleResponse(ret); int code = ret.getStatusLine().getStatusCode(); response.setStatus(code); ServletOutputStream output = response.getOutputStream(); output.write(stringret.getBytes(), 0, stringret.length()); output.close(); client.close(); /* HttpURLConnection connection = CreateConnection( urlTarget, request ); /// Helping construct Json connection.setRequestProperty("referer", origin); /// Send post data ServletInputStream inputData = request.getInputStream(); DataOutputStream writer = new DataOutputStream(connection.getOutputStream()); byte[] buffer = new byte[1024]; int dataSize; while( (dataSize = inputData.read(buffer,0,buffer.length)) != -1 ) { writer.write(buffer, 0, dataSize); } inputData.close(); writer.close(); RetrieveAnswer(connection, response, origin); //*/ } else { response.reset(); response.setHeader("Content-Disposition", "attachment; filename=generated" + ext); response.setContentType(format); response.setContentLength(out.size()); response.getOutputStream().write(out.toByteArray()); response.getOutputStream().flush(); } } catch (Exception e) { String message = e.getMessage(); response.setStatus(500); response.getOutputStream().write(message.getBytes()); response.getOutputStream().close(); e.printStackTrace(); } finally { dataProvider.disconnect(); } }
From source file:net.di2e.ecdr.search.transform.atom.AbstractAtomTransformer.java
@Override public BinaryContent transform(SourceResponse response, Map<String, Serializable> properties) throws CatalogTransformerException { if (properties == null) { properties = new HashMap<String, Serializable>(); }//from w w w .j a va 2 s. com ClassLoader currentClassLoader = Thread.currentThread().getContextClassLoader(); Feed feed = null; // The Adbera.getInstance.newFeed() spins up a new thread so must do // this try { Thread.currentThread().setContextClassLoader(AbstractAtomTransformer.class.getClassLoader()); feed = Abdera.getInstance().newFeed(); } finally { Thread.currentThread().setContextClassLoader(currentClassLoader); } feed.declareNS(AtomResponseConstants.CDRB_NAMESPACE, AtomResponseConstants.CDRB_NAMESPACE_PREFIX); feed.declareNS(AtomResponseConstants.CDRS_EXT_NAMESPACE, AtomResponseConstants.CDRS_EXT_NAMESPACE_PREFIX); feed.newId(); setFeedTitle(feed, properties); feed.setUpdated(new Date()); List<Result> results = response.getResults(); QueryRequest queryRequest = response.getRequest(); feed.addExtension(OpenSearchConstants.ITEMS_PER_PAGE).setText(String.valueOf(results.size())); feed.addExtension(OpenSearchConstants.START_INDEX) .setText(String.valueOf(queryRequest.getQuery().getStartIndex())); feed.addExtension(OpenSearchConstants.TOTAL_RESULTS).setText(String.valueOf(response.getHits())); feed.setGenerator(null, SystemInfo.getVersion(), SystemInfo.getSiteName()); feed.addAuthor(SystemInfo.getOrganization(), SystemInfo.getSiteContatct(), null); addLinksToFeed(feed, properties); if (!isFalse((Boolean) properties.get(SearchConstants.STATUS_PARAMETER))) { addStatus(response, feed, results, properties); } addFeedElements(feed, response, properties); Entry entry = null; for (Result result : results) { String id = null; try { Metacard metacard = result.getMetacard(); CDRMetacard cdrMetacard = new CDRMetacard(metacard); id = cdrMetacard.getId(); entry = getMetacardEntry(cdrMetacard, properties); Double relevance = result.getRelevanceScore(); if (relevance != null) { Element relevanceElement = entry.addExtension(new QName( AtomResponseConstants.RELEVANCE_NAMESPACE, AtomResponseConstants.RELEVANCE_ELEMENT, AtomResponseConstants.RELEVANCE_NAMESPACE_PREFIX)); relevanceElement.setText(String.valueOf(relevance)); } Double distance = result.getDistanceInMeters(); if (distance != null) { Element distanceElement = entry.addExtension(new QName(AtomResponseConstants.CDRS_EXT_NAMESPACE, AtomResponseConstants.DISTANCE_ELEMENT, AtomResponseConstants.CDRS_EXT_NAMESPACE_PREFIX)); distanceElement.setText(String.valueOf(distance)); } feed.addEntry(entry); } catch (Exception e) { LOGGER.warn( "WARNING - Could not properly transform metacard with id {} because ran into error '{}'. Please turn on DEBUG logging for more details", id, e.getMessage()); LOGGER.debug(e.getMessage(), e); } } BinaryContent binaryContent = null; try { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); // Feed writeTo spins up a new thread so must do this currentClassLoader = Thread.currentThread().getContextClassLoader(); try { Thread.currentThread().setContextClassLoader(AbstractAtomTransformer.class.getClassLoader()); feed.writeTo(outputStream); } finally { Thread.currentThread().setContextClassLoader(currentClassLoader); } 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:com.clarkparsia.pelletserver.client.utils.PelletServerUtils.java
/** * Parse the {@link MimeType}s from a services' {@link JSONObject} *///w w w. j av a2s .c o m private static MimeType[] parseMimeTypes(JSONObject service) throws JSONException, MimeTypeParseException { JSONArray mimetypes = service.getJSONArray("response-mimetype"); MimeType[] res = new MimeType[mimetypes.length()]; for (int i = 0; i < mimetypes.length(); i++) { res[i] = new MimeType(mimetypes.getString(i)); } return res; }
From source file:org.codice.ddf.spatial.ogc.catalog.resource.impl.ResourceReaderTest.java
/** * Tests the case in which the mime type of the Resource in the ResourceResponse returned by the * URLResourceReader is not text/html, application/unknown or application/octet-stream. The * original response from the URLResourceReader is returned. *//*from w w w .j a va2s . co m*/ @Test public void testRetrieveResourceOriginalUrlResourceReaderResponseReturned() throws Exception { // Setup String httpUriStr = HTTP_SCHEME_PLUS_SEP + MOCK_HTTP_SERVER_HOST + ":" + MOCK_HTTP_SERVER_PORT + MOCK_HTTP_SERVER_PATH; URI uri = new URI(httpUriStr); ResourceResponse mockResourceResponse = getMockResourceResponse(new MimeType("image/jpeg")); URLResourceReader mockUrlResourceReader = getMockUrlResourceReader(uri, mockResourceResponse); setupMockTika(null); OgcUrlResourceReader resourceReader = new OgcUrlResourceReader(mockUrlResourceReader, mockTika); HashMap<String, Serializable> arguments = new HashMap<String, Serializable>(); // Perform Test ResourceResponse resourceResponse = resourceReader.retrieveResource(uri, arguments); // Verify assertThat(resourceResponse, is(mockResourceResponse)); }
From source file:org.unitedinternet.cosmo.dav.impl.StandardDavRequest.java
/** * /* w w w . jav a 2 s.com*/ * @param requireDocument boolean * @return Document * @throws CosmoDavException */ private Document getSafeRequestDocument(boolean requireDocument) throws CosmoDavException { try { if (StringUtils.isBlank(getContentType()) && requireDocument) { throw new BadRequestException("No Content-Type specified"); } MimeType mimeType = new MimeType(getContentType()); if (!(mimeType.match(APPLICATION_XML) || mimeType.match(TEXT_XML))) { throw new UnsupportedMediaTypeException( "Expected Content-Type " + APPLICATION_XML + " or " + TEXT_XML); } return getRequestDocument(); } catch (MimeTypeParseException e) { throw new UnsupportedMediaTypeException(e.getMessage()); } catch (IllegalArgumentException e) { throwBadRequestExceptionFrom(e); } catch (DavException e) { throwBadRequestExceptionFrom(e); } return null; }
From source file:ddf.content.endpoint.rest.ContentEndpointCreateTest.java
protected ContentItem getMockGoodContentItem(String content, String fileName, String contentId, Long size, String mimeType) throws IOException, MimeTypeParseException { ContentItem item = mock(ContentItem.class); when(item.getInputStream()).thenReturn(new ByteArrayInputStream(content.getBytes())); when(item.getFilename()).thenReturn(fileName); when(item.getId()).thenReturn(contentId); if (size != null) { when(item.getSize()).thenReturn(size); } else {//from w w w. j av a 2s . co m when(item.getSize()).thenThrow(new IOException("IOException")); } when(item.getMimeTypeRawData()).thenReturn(mimeType); if (mimeType != null) { when(item.getMimeType()).thenReturn(new MimeType(mimeType)); } return item; }
From source file:ddf.catalog.impl.operations.OperationsCrudSupport.java
private Metacard generateMetacard(String mimeTypeRaw, String id, String fileName, Subject subject, Path tmpContentPath) throws MetacardCreationException, MimeTypeParseException { Metacard generatedMetacard = null;/*w w w .j av a 2 s . c o m*/ 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 = Optional.ofNullable(SubjectUtils.getName(subject)).orElse(""); generatedMetacard.setAttribute(new AttributeImpl(Metacard.POINT_OF_CONTACT, name)); return generatedMetacard; }
From source file:ddf.catalog.transformer.resource.ResourceMetacardTransformerTest.java
private MimeType getMimeType(String mimeTypeStr) throws Exception { return new MimeType(mimeTypeStr); }