List of usage examples for java.net URLConnection getContentType
public String getContentType()
From source file:org.sensorML.process.WMS_Process.java
/** * Executes process algorithm on inputs and set output data *///w w w . j a va 2s .c o m public void execute() throws ProcessException { RenderedImage renderedImage = null; try { initRequest(); //switchBytes(); if (log.isDebugEnabled()) log.debug(owsUtils.buildURLQuery(request)); URLConnection urlCon = owsUtils.sendGetRequest(request); // Check on mimeType catches all three types (blank, inimage, xml) // of OGC service exceptions String mimeType = urlCon.getContentType(); if (mimeType.contains("xml") || mimeType.startsWith("application")) { OGCExceptionReader reader = new OGCExceptionReader(); reader.parseException(urlCon.getInputStream()); } else { // use JAI MemorySeekableStream for better performance dataStream = new MemoryCacheSeekableStream(urlCon.getInputStream()); // Create the ParameterBlock and add the SeekableStream to it. ParameterBlock pb = new ParameterBlock(); pb.add(dataStream); // decode image using JAI RenderedOp rop = JAI.create("stream", pb); if (rop != null) { renderedImage = rop.createInstance(); // put data buffer in output datablock byte[] data = ((DataBufferByte) renderedImage.getData().getDataBuffer()).getData(); ((DataBlockByte) outputImage.getData()).setUnderlyingObject(data); } } // adjust width and height of the output int width = 0; int height = 0; if (renderedImage != null) { width = renderedImage.getWidth(); height = renderedImage.getHeight(); } outputWidth.getData().setIntValue(width); outputHeight.getData().setIntValue(height); output.combineDataBlocks(); } catch (Exception e) { throw new ProcessException("Error while requesting data from WMS server: " + request.getGetServer(), e); } finally { endRequest(); } }
From source file:com.artglorin.web.utils.XmlByteExtractor.java
private List<Description> extract(String tagName, String valueAttr) throws ExtractionException { NodeList tags = document.getElementsByTagName(tagName); List<Description> result = new ArrayList<>(tags.getLength()); byte[] data;/*w ww.j a v a 2s. c om*/ String type, extension, value, decodeType; Node node; for (int i = 0; i < tags.getLength(); i++) { node = tags.item(i); value = node.getAttributes().getNamedItem(valueAttr).getNodeValue(); if (value.startsWith("data:")) { try { type = value.substring(value.indexOf(":") + 1, value.indexOf("/")); } catch (Exception e) { throw new InvalidTypeException(value); } try { extension = value.substring(value.indexOf("/") + 1, value.indexOf(";")); } catch (Exception e) { throw new InvalidExtensionException(value); } try { decodeType = value.substring(value.indexOf(";") + 1, value.indexOf(",")); } catch (Exception e) { throw new InvalidDecodeTypeException(value); } if (decodeType.equals("base64")) { try { data = Base64.getDecoder().decode(value.substring(value.indexOf(",") + 1)); } catch (Exception e) { throw new DecodeException(e.toString()); } } else { throw new InvalidDecodeTypeException(decodeType); } result.add(new Description().setData(data).setExtension(extension).setNode(node).setType(type)); } else if (value.startsWith("http:") || value.startsWith("https:")) { URL url; try { url = new URL(value); } catch (MalformedURLException e) { e.printStackTrace(); throw new ExtractionException("Cannot create URL. Exception: " + e.toString()); } URLConnection connection; try { connection = url.openConnection(); } catch (IOException e) { throw new ExtractionException("Cannot open connection"); } String contentType = connection.getContentType(); if (contentType.toLowerCase().startsWith("image/") || contentType.toLowerCase().startsWith("audio/") || contentType.toLowerCase().startsWith("video/")) { type = contentType.substring(0, contentType.indexOf("/")); extension = contentType.substring(contentType.indexOf("/") + 1); try { data = IOUtils.toByteArray(connection.getInputStream()); } catch (IOException e) { throw new ExtractionException("Cannot get bytes from source: " + value); } result.add(new Description().setData(data).setExtension(extension).setType(type).setNode(node)); } else { throw new InvalidTypeException(contentType); } } else { throw new UnsupportedFormatException(value); } } return result; }
From source file:org.mycore.datamodel.ifs.MCRAudioVideoExtender.java
/** * Helper method that connects to the given URL and returns the response as * a String//from ww w . j a v a2s.com * * @param url * the URL to connect to * @return the response content as a String */ protected String getMetadata(String url) throws MCRPersistenceException { try { URLConnection connection = getConnection(url); connection.setConnectTimeout(getConnectTimeout()); String contentType = connection.getContentType(); Charset charset = StandardCharsets.ISO_8859_1; //defined by RFC 2616 (sec 3.7.1) if (contentType != null) { MediaType mediaType = MediaType.parse(contentType); mediaType.charset().or(StandardCharsets.ISO_8859_1); } ByteArrayOutputStream out = new ByteArrayOutputStream(1024); forwardData(connection, out); return new String(out.toByteArray(), charset); } catch (IOException exc) { String msg = "Could not get metadata from Audio/Video Store URL: " + url; throw new MCRPersistenceException(msg, exc); } }
From source file:org.voyanttools.trombone.input.source.UriInputSource.java
/** * Create a new instance with the specified URI. * //from w w w . j a v a 2s . co m * @param uri the URI associated with this input source * @throws IOException * thrown when there's a problem creating or accessing header * information for the URI * @throws MalformedURLException * thrown if the URI is malformed */ public UriInputSource(URI uri) throws IOException { this.uri = uri; this.metadata = new DocumentMetadata(); this.metadata.setLocation(uri.toString()); this.metadata.setSource(Source.URI); String path = uri.getPath(); if (path.isEmpty() || path.equals("/")) { // no path, use host metadata.setTitle(uri.getHost()); } else if (path.endsWith("/")) { // ends in slash, use full path metadata.setTitle(path); } else { // try to use file part of URI metadata.setTitle(new File(path).getName()); } StringBuilder idBuilder = new StringBuilder(uri.toString()); // establish connection to find other and default metadata URLConnection c = null; try { c = getURLConnection(uri, 15000, 10000); // last modified of file long modified = c.getLastModified(); this.metadata.setModified(modified); idBuilder.append(modified); // try and get length for id int length = c.getContentLength(); idBuilder.append(length); String format = c.getContentType(); if (format != null && format.isEmpty() == false) { idBuilder.append(format); DocumentFormat docFormat = DocumentFormat.fromContentType(format); if (docFormat != DocumentFormat.UNKNOWN) { this.metadata.setDefaultFormat(docFormat); } } } finally { if (c != null && c instanceof HttpURLConnection) { ((HttpURLConnection) c).disconnect(); } } this.id = DigestUtils.md5Hex(idBuilder.toString()); }
From source file:com.sun.socialsite.web.rest.core.GroupProfilesHandler.java
private boolean downloadImage(String imageLocation, Group grp) { try {/* w ww . jav a2s.c o m*/ URLConnection conn = new URL(imageLocation).openConnection(); InputStream inp = conn.getInputStream(); ByteArrayOutputStream bos = new ByteArrayOutputStream(); Utilities.copyInputToOutput(inp, bos); byte[] byteArray = bos.toByteArray(); grp.setImageType(conn.getContentType()); grp.setImage(byteArray); } catch (Exception ex) { return false; } return true; }
From source file:org.silverpeas.mobile.server.servlets.PublicationContentServlet.java
private String convertSpImageUrlToDataUrl(String url) { String data = url;/*from w w w. ja va 2 s .co m*/ if (url.contains("GalleryInWysiwyg")) { try { String instanceId = url.substring(url.indexOf("ComponentId") + "ComponentId".length() + 1); instanceId = instanceId.substring(0, instanceId.indexOf("&")); String imageId = url.substring(url.indexOf("ImageId") + "ImageId".length() + 1); imageId = imageId.substring(0, imageId.indexOf("&")); Photo photo = getGalleryService().getPhoto(new MediaPK(imageId)); String[] rep = { "image" + imageId }; String path = FileRepositoryManager.getAbsolutePath(null, instanceId, rep); File f = new File(path + photo.getFileName()); FileInputStream is = new FileInputStream(f); byte[] binaryData = new byte[(int) f.length()]; is.read(binaryData); is.close(); data = "data:" + photo.getFileMimeType() + ";base64," + new String(Base64.encodeBase64(binaryData)); } catch (Exception e) { SilverLogger.getLogger(SpMobileLogModule.getName()) .error("PublicationContentServlet.convertSpImageUrlToDataUrl", "root.EX_NO_MESSAGE", e); } } else if (url.contains("attachmentId")) { data = convertImageAttachmentUrl(url, data); } else { try { if (url.startsWith("/silverpeas")) { url = rootContext + url; } URL urlObject = new URL(url); URLConnection connection = urlObject.openConnection(); connection.connect(); String contentType = connection.getContentType(); byte[] binaryData = new byte[(int) connection.getInputStream().available()]; connection.getInputStream().read(binaryData); data = "data:" + contentType + ";base64," + new String(Base64.encodeBase64(binaryData)); } catch (Exception e) { SilverLogger.getLogger(SpMobileLogModule.getName()) .error("PublicationContentServlet.convertImageUrlToDataUrl", "root.EX_NO_MESSAGE", e); // If can't connect to url, return the url without change } } return data; }
From source file:org.geoserver.wms.web.data.ExternalGraphicPanel.java
/** * @param id/* w ww. ja va 2s . c o m*/ * @param model Must return a {@link ResourceInfo} */ public ExternalGraphicPanel(String id, final CompoundPropertyModel<StyleInfo> styleModel, final Form<?> styleForm) { super(id, styleModel); // container for ajax updates final WebMarkupContainer container = new WebMarkupContainer("externalGraphicContainer"); container.setOutputMarkupId(true); add(container); table = new WebMarkupContainer("list"); table.setOutputMarkupId(true); IModel<String> bind = styleModel.bind("legend.onlineResource"); onlineResource = new TextField<String>("onlineResource", bind); onlineResource.add(new IValidator<String>() { final List<String> EXTENSIONS = Arrays.asList(new String[] { "png", "gif", "jpeg", "jpg" }); @Override public void validate(IValidatable<String> input) { String value = input.getValue(); int last = value == null ? -1 : value.lastIndexOf('.'); if (last == -1 || !EXTENSIONS.contains(value.substring(last + 1).toLowerCase())) { ValidationError error = new ValidationError(); error.setMessage("Not an image"); error.addKey("nonImage"); input.error(error); return; } URI uri = null; try { uri = new URI(value); } catch (URISyntaxException e1) { // Unable to check if absolute } if (uri != null && uri.isAbsolute()) { try { String baseUrl = baseURL(onlineResource.getForm()); if (!value.startsWith(baseUrl)) { onlineResource.warn("Recommend use of styles directory at " + baseUrl); } URL url = uri.toURL(); URLConnection conn = url.openConnection(); if ("text/html".equals(conn.getContentType())) { ValidationError error = new ValidationError(); error.setMessage("Unable to access image"); error.addKey("imageUnavailable"); input.error(error); return; // error message back! } } catch (MalformedURLException e) { ValidationError error = new ValidationError(); error.setMessage("Unable to access image"); error.addKey("imageUnavailable"); input.error(error); } catch (IOException e) { ValidationError error = new ValidationError(); error.setMessage("Unable to access image"); error.addKey("imageUnavailable"); input.error(error); } return; // no further checks possible } else { GeoServerResourceLoader resources = GeoServerApplication.get().getResourceLoader(); try { File styles = resources.find("styles"); String[] path = value.split(Pattern.quote(File.separator)); WorkspaceInfo wsInfo = styleModel.getObject().getWorkspace(); File test = null; if (wsInfo != null) { String wsName = wsInfo.getName(); List<String> list = new ArrayList(); list.addAll(Arrays.asList("workspaces", wsName, "styles")); list.addAll(Arrays.asList(path)); test = resources.find(list.toArray(new String[list.size()])); } if (test == null) { test = resources.find(styles, path); } if (test == null) { ValidationError error = new ValidationError(); error.setMessage("File not found in styles directory"); error.addKey("imageNotFound"); input.error(error); } } catch (IOException e) { ValidationError error = new ValidationError(); error.setMessage("File not found in styles directory"); error.addKey("imageNotFound"); input.error(error); } } } }); onlineResource.setOutputMarkupId(true); table.add(onlineResource); // add the autofill button autoFill = new GeoServerAjaxFormLink("autoFill", styleForm) { @Override public void onClick(AjaxRequestTarget target, Form<?> form) { URLConnection conn = getExternalGraphic(target, form); if (conn == null) { ValidationError error = new ValidationError(); error.setMessage("Unable to access image"); error.addKey("imageUnavailable"); onlineResource.error(error); } else { format.setModelValue(new String[] { conn.getContentType() }); BufferedImage image; try { image = ImageIO.read(conn.getInputStream()); width.setModelValue(new String[] { "" + image.getWidth() }); height.setModelValue(new String[] { "" + image.getHeight() }); } catch (IOException e) { e.printStackTrace(); } target.add(format); target.add(width); target.add(height); } } }; table.add(autoFill); format = new TextField<String>("format", styleModel.bind("legend.format")); format.setOutputMarkupId(true); table.add(format); width = new TextField<Integer>("width", styleModel.bind("legend.width"), Integer.class); width.add(RangeValidator.minimum(0)); width.setRequired(true); width.setOutputMarkupId(true); table.add(width); height = new TextField<Integer>("height", styleModel.bind("legend.height"), Integer.class); height.add(RangeValidator.minimum(0)); height.setRequired(true); height.setOutputMarkupId(true); table.add(height); table.add(new AttributeModifier("style", showhideStyleModel)); container.add(table); showhideForm = new Form<StyleInfo>("showhide") { @Override protected void onSubmit() { super.onSubmit(); } }; showhideForm.setMarkupId("showhideForm"); container.add(showhideForm); showhideForm.setMultiPart(true); show = new AjaxButton("show") { private static final long serialVersionUID = 1L; @Override protected void onSubmit(AjaxRequestTarget target, Form<?> form) { updateVisibility(true); target.add(ExternalGraphicPanel.this); } }; container.add(show); showhideForm.add(show); hide = new AjaxButton("hide") { private static final long serialVersionUID = 1L; @Override protected void onSubmit(AjaxRequestTarget target, Form<?> form) { onlineResource.setModelObject(""); onlineResource.clearInput(); format.setModelObject(""); format.clearInput(); width.setModelObject(0); width.clearInput(); height.setModelObject(0); height.clearInput(); updateVisibility(false); target.add(ExternalGraphicPanel.this); } }; container.add(hide); showhideForm.add(hide); LegendInfo legend = styleModel.getObject().getLegend(); boolean visible = legend != null && legend.getOnlineResource() != null && !legend.getOnlineResource().isEmpty(); updateVisibility(visible); }
From source file:org.apache.cocoon.components.search.SimpleLuceneXMLIndexerImpl.java
/** * Build lucenen documents from a URL/*from w w w . ja va 2s .c o m*/ * * @param url the content of this url gets indexed. * @exception ProcessingException Description of Exception * @since */ public List build(URL url) throws ProcessingException { try { URL contentURL = new URL(url, url.getFile() + ((url.getFile().indexOf("?") == -1) ? "?" : "&") + contentViewQuery); URLConnection contentURLConnection = contentURL.openConnection(); if (contentURLConnection == null) { throw new ProcessingException( "Can not open connection to URL " + contentURL + " (null connection)"); } String contentType = contentURLConnection.getContentType(); if (contentType == null) { if (getLogger().isDebugEnabled()) { getLogger().debug("Ignoring " + contentURL + " (no content type)"); } return Collections.EMPTY_LIST; } int index = contentType.indexOf(';'); if (index != -1) { contentType = contentType.substring(0, index); } if (allowedContentType.contains(contentType)) { if (getLogger().isDebugEnabled()) { getLogger().debug("Indexing " + contentURL + " (" + contentType + ")"); } LuceneIndexContentHandler luceneIndexContentHandler = new LuceneIndexContentHandler(); luceneIndexContentHandler.setFieldTags(fieldTags); indexDocument(contentURLConnection, luceneIndexContentHandler); // // document is parsed // Iterator it = luceneIndexContentHandler.iterator(); while (it.hasNext()) { Document d = (Document) it.next(); d.add(Field.UnIndexed(URL_FIELD, url.toString())); // store ... false, index ... true, token ... false d.add(new Field(UID_FIELD, uid(contentURLConnection), false, true, false)); } return luceneIndexContentHandler.allDocuments(); } else { if (getLogger().isDebugEnabled()) { getLogger().debug("Ignoring " + contentURL + " (" + contentType + ")"); } return Collections.EMPTY_LIST; } } catch (IOException ioe) { throw new ProcessingException("Cannot read URL " + url, ioe); } }
From source file:com.xmlcalabash.io.ReadableData.java
protected InputStream getStream(URI uri) { try {/* w w w .j a va2 s .co m*/ URL url = uri.toURL(); URLConnection connection = url.openConnection(); serverContentType = connection.getContentType(); return connection.getInputStream(); } catch (IOException ioe) { throw new XProcException(XProcConstants.dynamicError(29), ioe); } }
From source file:org.speechforge.cairo.server.tts.MrcpSpeechSynthChannel.java
public synchronized MrcpResponse speak(UnimplementedRequest request, MrcpSession session) { MrcpRequestState requestState = MrcpRequestState.COMPLETE; short statusCode = -1; _logger.debug(request.getContent()); if (request.hasContent()) { String contentType = request.getContentType(); if (contentType.equalsIgnoreCase("text/plain")) { String text = request.getContent(); try { File promptFile = generatePrompt(text); int state = _rtpChannel.queuePrompt(promptFile, new Listener(session)); requestState = (state == RTPSpeechSynthChannel.IDLE) ? MrcpRequestState.IN_PROGRESS : MrcpRequestState.PENDING; statusCode = MrcpResponse.STATUS_SUCCESS; } catch (RuntimeException e) { _logger.debug(e, e);/*from w w w . j av a 2s . c o m*/ statusCode = MrcpResponse.STATUS_SERVER_INTERNAL_ERROR; } catch (InvalidSessionAddressException e) { _logger.debug(e, e); statusCode = MrcpResponse.STATUS_OPERATION_FAILED; } catch (IOException e) { _logger.debug(e, e); statusCode = MrcpResponse.STATUS_OPERATION_FAILED; } } else if (contentType.equalsIgnoreCase("text/uri-list")) { String text = request.getContent(); String[] uris = text.split("\\r"); _logger.debug(text); //TODO: Handle multiple URI's in a URI list //should there be just one listener for the last prompt? for now limiting to one. if (uris.length > 1) { _logger.warn("Multiple URIs not supported yet. Just playing the first URI."); } //for (int i=0; i<uris.length;i++) { for (int i = 0; i < 1; i++) { try { URL url = new URL(uris[i]); URLConnection uc = url.openConnection(); _logger.debug(uris[i] + " " + uc.getContentType()); if (uc.getContentType().equals("text/plain")) { BufferedReader in = new BufferedReader(new InputStreamReader(uc.getInputStream())); //TODO: Make this more efficient String inputLine; String promptString = new String(); while ((inputLine = in.readLine()) != null) { promptString = promptString + inputLine; } in.close(); try { File promptFile = generatePrompt(promptString); int state = _rtpChannel.queuePrompt(promptFile, new Listener(session)); requestState = (state == RTPSpeechSynthChannel.IDLE) ? MrcpRequestState.IN_PROGRESS : MrcpRequestState.PENDING; statusCode = MrcpResponse.STATUS_SUCCESS; } catch (RuntimeException e) { _logger.debug(e, e); statusCode = MrcpResponse.STATUS_SERVER_INTERNAL_ERROR; break; } catch (InvalidSessionAddressException e) { _logger.debug(e, e); statusCode = MrcpResponse.STATUS_OPERATION_FAILED; break; } catch (IOException e) { _logger.debug(e, e); statusCode = MrcpResponse.STATUS_OPERATION_FAILED; break; } } else if ((uc.getContentType().equals("audio/x-wav")) || (uc.getContentType().equals("audio/basic"))) { try { File promptFile; //if file protocol url -- no need to copy it to the server else copy it if (url.getProtocol().equals("file")) { promptFile = new File(url.getFile()); } else { promptFile = copyPrompt(url); } int state = _rtpChannel.queuePrompt(promptFile, new Listener(session)); requestState = (state == RTPSpeechSynthChannel.IDLE) ? MrcpRequestState.IN_PROGRESS : MrcpRequestState.PENDING; statusCode = MrcpResponse.STATUS_SUCCESS; } catch (RuntimeException e) { _logger.debug(e, e); statusCode = MrcpResponse.STATUS_SERVER_INTERNAL_ERROR; break; } catch (InvalidSessionAddressException e) { _logger.debug(e, e); statusCode = MrcpResponse.STATUS_OPERATION_FAILED; break; } catch (IOException e) { _logger.debug(e, e); statusCode = MrcpResponse.STATUS_OPERATION_FAILED; break; } } else { _logger.warn( "Unsupported content type for in the speak request: " + uc.getContentType()); } } catch (MalformedURLException e) { _logger.debug(e, e); statusCode = MrcpResponse.STATUS_OPERATION_FAILED; } catch (IOException e) { _logger.debug(e, e); statusCode = MrcpResponse.STATUS_OPERATION_FAILED; } } } else { statusCode = MrcpResponse.STATUS_UNSUPPORTED_HEADER_VALUE; } } else { statusCode = MrcpResponse.STATUS_MANDATORY_HEADER_MISSING; } return session.createResponse(statusCode, requestState); }