List of usage examples for java.net URI toURL
public URL toURL() throws MalformedURLException
From source file:com.mirth.connect.connectors.ws.WebServiceDispatcher.java
/** * Returns the URL for the passed in String. If the URL requires authentication, then the WSDL * is saved as a temp file and the URL for that file is returned. * // ww w. j a v a 2s . c o m * @param wsdlUrl * @param username * @param password * @return * @throws Exception */ private URL getWsdlUrl(DispatchContainer dispatchContainer) throws Exception { URI uri = new URI(dispatchContainer.getCurrentWsdlUrl()); // If the URL points to file, just return it if (!uri.getScheme().equalsIgnoreCase("file")) { BasicHttpClientConnectionManager httpClientConnectionManager = new BasicHttpClientConnectionManager( socketFactoryRegistry.build()); httpClientConnectionManager.setSocketConfig(SocketConfig.custom().setSoTimeout(timeout).build()); HttpClientBuilder clientBuilder = HttpClients.custom() .setConnectionManager(httpClientConnectionManager); HttpUtil.configureClientBuilder(clientBuilder); CloseableHttpClient client = clientBuilder.build(); try { clients.add(client); HttpClientContext context = HttpClientContext.create(); if (dispatchContainer.getCurrentUsername() != null && dispatchContainer.getCurrentPassword() != null) { CredentialsProvider credsProvider = new BasicCredentialsProvider(); AuthScope authScope = new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT, AuthScope.ANY_REALM); Credentials credentials = new UsernamePasswordCredentials( dispatchContainer.getCurrentUsername(), dispatchContainer.getCurrentPassword()); credsProvider.setCredentials(authScope, credentials); AuthCache authCache = new BasicAuthCache(); RegistryBuilder<AuthSchemeProvider> registryBuilder = RegistryBuilder .<AuthSchemeProvider>create(); registryBuilder.register(AuthSchemes.BASIC, new BasicSchemeFactory()); context.setCredentialsProvider(credsProvider); context.setAuthSchemeRegistry(registryBuilder.build()); context.setAuthCache(authCache); } RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(timeout) .setSocketTimeout(timeout).setStaleConnectionCheckEnabled(true).build(); context.setRequestConfig(requestConfig); return getWsdl(client, context, dispatchContainer, new HashMap<String, File>(), dispatchContainer.getCurrentWsdlUrl()).toURI().toURL(); } finally { HttpClientUtils.closeQuietly(client); clients.remove(client); } } return uri.toURL(); }
From source file:it.geosolutions.geoserver.rest.GeoServerRESTPublisher.java
/** * Publish a collection of shapefiles./*from ww w.j a v a2 s . c o m*/ * <P> * Will automatically create the store and publish each shapefile as a layer. * * @param workspace the name of the workspace to use * @param storeName the name of the store to create * @param resource the shapefile collection. It can be: * <ul> * <li>A path to a directory containing shapefiles in the server. <li>A local zip file containing shapefiles that will be uploaded. <li>A * URL pointing to a shapefile collection in the wild web (not tested). * </ul> * @return {@code true} if publication successful. * @throws FileNotFoundException if the specified zip file does not exist. */ public boolean publishShpCollection(String workspace, String storeName, URI resource) throws FileNotFoundException { // Deduce upload method & mime type from resource syntax. UploadMethod method = null; String mime = null; if (resource.getScheme().equals("file") || resource.isAbsolute() == false) { File f = new File(resource); if (f.exists() && f.isFile() && f.toString().endsWith(".zip")) { method = UploadMethod.FILE; mime = "application/zip"; } else if (f.isDirectory()) { method = UploadMethod.EXTERNAL; mime = "text/plain"; } } else { try { if (resource.toURL() != null) { method = UploadMethod.URL; mime = "text/plain"; } } catch (MalformedURLException e) { throw new IllegalArgumentException( "Resource is not recognized as a zip file, or a directory, or a valid URL", e); } } // Create store, upload data, and publish layers return createStore(workspace, StoreType.DATASTORES, storeName, method, DataStoreExtension.SHP, mime, resource, ParameterConfigure.ALL, new NameValuePair[0]); }
From source file:eu.scape_project.service.ConnectorService.java
private List<String> addFiles(final Session session, final List<File> files, final String repPath) throws RepositoryException { if (files == null) { return Collections.<String>emptyList(); }/*from www . jav a 2 s . com*/ final List<String> fileUris = new ArrayList<>(files.size()); final StringBuilder sparql = new StringBuilder("PREFIX scape: <" + SCAPE_NAMESPACE + "> "); for (File f : files) { final String fileId = (f.getIdentifier() != null) ? f.getIdentifier().getValue() : UUID.randomUUID().toString(); final String filePath = repPath + "/" + fileId; URI fileUri = f.getUri(); if (fileUri.getScheme() == null) { fileUri = URI.create("file:" + fileUri.toASCIIString()); } /* create a datastream in fedora for this file */ final FedoraObject fileObject = this.objectService.createObject(session, filePath); fileObject.getNode().addMixin("scape:file"); final IdentifierTranslator subjects = new DefaultIdentifierTranslator(); final String uri = subjects.getSubject(fileObject.getPath()).getURI(); /* add the metadata */ if (f.getTechnical() != null) { addMetadata(session, f.getTechnical(), filePath + "/TECHNICAL"); } /* add all bitstreams as child objects */ if (f.getBitStreams() != null) { for (final String bsUri : addBitStreams(session, f.getBitStreams(), "/" + filePath)) { sparql.append("INSERT DATA {<" + uri + "> " + prefix(HAS_BITSTREAM) + " \"" + bsUri + "\"};"); } } String fileName = f.getFilename(); if (fileName == null) { fileName = f.getUri().toASCIIString().substring(f.getUri().toASCIIString().lastIndexOf('/') + 1); } final String mimeType = (f.getMimetype() != null) ? f.getMimetype() : "application/binary"; sparql.append("INSERT DATA {<" + uri + "> " + prefix(HAS_TYPE) + " \"file\"};"); sparql.append("INSERT DATA {<" + uri + "> " + prefix(HAS_FILENAME) + " \"" + fileName + "\"};"); sparql.append("INSERT DATA {<" + uri + "> " + prefix(HAS_MIMETYPE) + " \"" + mimeType + "\"};"); sparql.append("INSERT DATA {<" + uri + "> " + prefix(HAS_INGEST_SOURCE) + " \"" + f.getUri() + "\"};"); if (this.referencedContent) { /* only write a reference to the file URI as a node property */ sparql.append( "INSERT DATA {<" + uri + "> " + prefix(HAS_REFERENCED_CONTENT) + " \"" + fileUri + "\"};"); } else { /* load the actual binary data into the repo */ LOG.info("reading binary from {}", fileUri.toASCIIString()); try (final InputStream src = fileUri.toURL().openStream()) { final Node fileDs = this.datastreamService .createDatastream(session, filePath + "/DATA", f.getMimetype(), null, src) .getContentNode(); } catch (IOException | InvalidChecksumException e) { throw new RepositoryException(e); } } fileUris.add(uri); fileObject.updatePropertiesDataset(subjects, sparql.toString()); } return fileUris; }
From source file:de.unigoettingen.sub.commons.contentlib.servlet.controller.GetImageAction.java
public ImageHolder getImageHolder(Map<String, String[]> params) throws URISyntaxException, IOException, ImageManagerException { /*/*from w ww .j a v a2 s . c o m*/ * -------------------------------- get central configuration -------------------------------- */ URI sourceImageUrl = null; ContentServerConfiguration config = ContentServerConfiguration.getInstance(); if (!params.get("sourcepath")[0].startsWith("file:") && !params.get("sourcepath")[0].startsWith("http:")) { String path = params.get("sourcepath")[0].replace(" ", "+"); sourceImageUrl = new URI(config.getRepositoryPathImages() + path); } else { String path = params.get("sourcepath")[0].replace(" ", "+"); sourceImageUrl = new URI(path); } try { Cache cc = null; // ServletOutputStream output = response.getOutputStream(); if (params.get("thumbnail") != null) { cc = ContentServer.getThumbnailCache(); } else { cc = ContentServer.getContentCache(); } String myUniqueID = getContentCacheIdForParamMap(params, config); LOGGER.trace("myUniqueId: " + myUniqueID); String targetExtension = params.get("format")[0]; boolean ignoreCache = false; /* check if cache should be ignored */ if (params.get("ignoreCache") != null) { String ignore = params.get("ignoreCache")[0].trim(); ignoreCache = Boolean.parseBoolean(ignore); } boolean useCache = false; if (params.get("thumbnail") != null) { useCache = config.getThumbnailCacheUse(); } else { useCache = config.getContentCacheUse(); } if (params.get("highlight") != null) { useCache = false; } if (cc == null || !useCache || params.get("highlight") != null) { ignoreCache = true; cc = null; LOGGER.debug("cache deactivated via configuration"); } // Image found in cache if (!ignoreCache && cc.isKeyInCache(myUniqueID + "." + targetExtension)) { LOGGER.debug("get file from cache: " + myUniqueID + "." + targetExtension); try { CacheObject co = (CacheObject) cc.get(myUniqueID + "." + targetExtension).getValue(); return new ImageHolder(co.getData()); } catch (NullPointerException e) { LOGGER.debug("element not in cache anymore: " + myUniqueID + "." + targetExtension); } // if (!ignoreCache && cc.isKeyInCache(myUniqueID + "." + targetExtension)) { // LOGGER.debug("get file from cache: " + myUniqueID); // // RenderedImage ri = (RenderedImage) cc.get(myUniqueID + "." + targetExtension).getObjectValue(); // JpegInterpreter ii = new JpegInterpreter(ri); // ii.writeToStream(null, baos); // return baos.toByteArray(); } else if (!ignoreCache) { LOGGER.debug("file not found in cache: " + myUniqueID + "." + targetExtension); } /* * -------------------------------- retrieve source image from url -------------------------------- */ ImageManager sourcemanager = new ImageManager(sourceImageUrl.toURL()); LOGGER.trace("imageManager initialized"); /* * -------------------------------- set the defaults -------------------------------- */ int angle = 0; int scaleX = 100; int scaleY = 100; int scaleType = ImageManager.SCALE_BY_PERCENT; LinkedList<String> highlightCoordinateList = null; Color highlightColor = null; Watermark myWatermark = null; LOGGER.trace("Variables set"); /* * -------------------------------- rotate -------------------------------- */ if (params.get("rotate") != null) { angle = Integer.parseInt(params.get("rotate")[0]); LOGGER.trace("rotate image:" + angle); } /* * -------------------------------- scale: scale the image to some percent value -------------------------------- */ if (params.get("scale") != null) { scaleX = Integer.parseInt(params.get("scale")[0]); scaleY = scaleX; scaleType = ImageManager.SCALE_BY_PERCENT; LOGGER.trace("scale image to percent:" + scaleX); } if (params.get("width") != null && params.get("height") != null) { scaleX = Integer.parseInt(params.get("width")[0]); scaleY = Integer.parseInt(params.get("height")[0]); scaleType = ImageManager.SCALE_TO_BOX; } /* * -------------------------------- width: scale image to fixed width -------------------------------- */ else if (params.get("width") != null) { scaleX = Integer.parseInt(params.get("width")[0]); scaleY = 0; scaleType = ImageManager.SCALE_BY_WIDTH; LOGGER.trace("scale image to width:" + scaleX); } /* * -------------------------------- height: scale image to fixed height -------------------------------- */ else if (params.get("height") != null) { scaleY = Integer.parseInt(params.get("height")[0]); scaleX = 0; scaleType = ImageManager.SCALE_BY_HEIGHT; LOGGER.trace("scale image to height:" + scaleY); } /* * -------------------------------- highlight -------------------------------- */ if (params.get("highlight") != null) { highlightCoordinateList = new LinkedList<String>(); String highlight = params.get("highlight")[0]; StrTokenizer areas = new StrTokenizer(highlight, "$"); for (String area : areas.getTokenArray()) { StrTokenizer coordinates = new StrTokenizer(area, ","); highlightCoordinateList.add(coordinates.getContent()); } highlightColor = config.getDefaultHighlightColor(); } /* * -------------------------------- insert watermark, if it should be used -------------------------------- */ if (params.get("ignoreWatermark") == null) { if (config.getWatermarkUse()) { File watermarkfile = new File(new URI(config.getWatermarkConfigFilePath())); myWatermark = Watermark.generateWatermark(params, watermarkfile); } } /* * -------------------------------- prepare target -------------------------------- */ // change to true if watermark should scale boolean scaleWatermark = false; if (config.getScaleWatermark()) { scaleWatermark = true; } RenderedImage targetImage = sourcemanager.scaleImageByPixel(scaleX, scaleY, scaleType, angle, highlightCoordinateList, highlightColor, myWatermark, scaleWatermark, ImageManager.BOTTOM); LOGGER.trace("Creating ImageInterpreter"); ImageFileFormat targetFormat = ImageFileFormat.getImageFileFormatFromFileExtension(targetExtension); ImageInterpreter wi = targetFormat.getInterpreter(targetImage); // read file LOGGER.trace("Image stored in " + wi.getClass().getCanonicalName()); /* * -------------------------------- set file name and attachment header from parameter or from configuration * -------------------------------- */ // StringBuilder targetFileName = new StringBuilder(); // if (config.getSendImageAsAttachment()) { // targetFileName.append("attachment; "); // } // targetFileName.append("filename="); // // if (params.get("targetFileName") != null) { // targetFileName.append(params.get("targetFileName")); // } else { // String filename = ContentLibUtil.getCustomizedFileName(config.getDefaultFileNameImages(), "." + // targetFormat.getFileExtension()); // targetFileName.append(filename); // } /* * -------------------------------- resolution -------------------------------- */ LOGGER.trace("Setting image resolution"); if (params.get("resolution") != null) { wi.setXResolution(Float.parseFloat(params.get("resolution")[0])); wi.setYResolution(Float.parseFloat(params.get("resolution")[0])); // TODO Is this correct? } else { wi.setXResolution(config.getDefaultResolution()); wi.setYResolution(config.getDefaultResolution()); } LOGGER.trace("Finished setting image resolution"); /* * -------------------------------- write target image to stream -------------------------------- */ byte[] data = wi.writeToStreamAndByteArray(new ByteArrayOutputStream()); ImageHolder returnImage = new ImageHolder(data, wi.getWidth(), wi.getHeight()); if (cc != null && highlightColor == null) { cc.putIfAbsent(new Element(myUniqueID + "." + targetExtension, new CacheObject(data))); } LOGGER.trace("Done writing image to stream"); return returnImage; } catch (CacheException e) { LOGGER.error("CacheException", e); } catch (MalformedURLException e) { LOGGER.error(e.getMessage(), e); } catch (ImageManipulatorException e) { LOGGER.error(e.getMessage(), e); } catch (WatermarkException e) { LOGGER.error(e.getMessage(), e); } return null; }
From source file:org.gege.caldavsyncadapter.syncadapter.SyncAdapter.java
/** * checks the android events for the dirty flag. * the flag is set by android when the event has been changed. * the dirty flag is removed when an android event has been updated from calendar event * @param provider/*from w w w . jav a 2 s .c om*/ * @param account * @param calendarUri * @param facade * @param caldavCalendarUri * @param stats * @param notifyList * @return count of dirty events */ private int checkDirtyAndroidEvents(ContentProviderClient provider, Account account, Uri calendarUri, CaldavFacade facade, URI caldavCalendarUri, SyncStats stats, ArrayList<Uri> notifyList) { Cursor curEvent = null; Cursor curAttendee = null; Cursor curReminder = null; Long EventID; Long CalendarID; AndroidEvent androidEvent = null; int rowDirty = 0; int rowInsert = 0; int rowUpdate = 0; int rowDelete = 0; try { CalendarID = ContentUris.parseId(calendarUri); String selection = "(" + Events.DIRTY + " = ?) AND (" + Events.CALENDAR_ID + " = ?)"; String[] selectionArgs = new String[] { "1", CalendarID.toString() }; curEvent = provider.query(Events.CONTENT_URI, null, selection, selectionArgs, null); while (curEvent.moveToNext()) { EventID = curEvent.getLong(curEvent.getColumnIndex(Events._ID)); Uri returnedUri = ContentUris.withAppendedId(Events.CONTENT_URI, EventID); androidEvent = new AndroidEvent(account, provider, returnedUri, calendarUri); androidEvent.readContentValues(curEvent); selection = "(" + Attendees.EVENT_ID + " = ?)"; selectionArgs = new String[] { String.valueOf(EventID) }; curAttendee = provider.query(Attendees.CONTENT_URI, null, selection, selectionArgs, null); selection = "(" + Reminders.EVENT_ID + " = ?)"; selectionArgs = new String[] { String.valueOf(EventID) }; curReminder = provider.query(Reminders.CONTENT_URI, null, selection, selectionArgs, null); androidEvent.readAttendees(curAttendee); androidEvent.readReminder(curReminder); curAttendee.close(); curReminder.close(); String SyncID = androidEvent.ContentValues.getAsString(Events._SYNC_ID); boolean Deleted = false; int intDeleted = 0; intDeleted = curEvent.getInt(curEvent.getColumnIndex(Events.DELETED)); Deleted = (intDeleted == 1); if (SyncID == null) { // new Android event String newGUID = java.util.UUID.randomUUID().toString() + "-caldavsyncadapter"; String calendarPath = caldavCalendarUri.getPath(); if (!calendarPath.endsWith("/")) calendarPath += "/"; SyncID = calendarPath + newGUID + ".ics"; androidEvent.createIcs(newGUID); if (facade.createEvent(URI.create(SyncID), androidEvent.getIcsEvent().toString())) { //HINT: bugfix for google calendar if (SyncID.contains("@")) SyncID = SyncID.replace("@", "%40"); ContentValues values = new ContentValues(); values.put(Events._SYNC_ID, SyncID); //google doesn't send the etag after creation //HINT: my SabreDAV send always the same etag after putting a new event //String LastETag = facade.getLastETag(); //if (!LastETag.equals("")) { // values.put(Event.ETAG, LastETag); //} else { //so get the etag with a new REPORT CalendarEvent calendarEvent = new CalendarEvent(account, provider); calendarEvent.calendarURL = caldavCalendarUri.toURL(); URI SyncURI = new URI(SyncID); calendarEvent.setUri(SyncURI); CaldavFacade.getEvent(calendarEvent); values.put(Event.ETAG, calendarEvent.getETag()); //} values.put(Event.UID, newGUID); values.put(Events.DIRTY, 0); values.put(Event.RAWDATA, androidEvent.getIcsEvent().toString()); int rowCount = provider.update( asSyncAdapter(androidEvent.getUri(), account.name, account.type), values, null, null); if (rowCount == 1) { rowInsert += 1; notifyList.add(androidEvent.getUri()); } } } else if (Deleted) { // deleted Android event if (facade.deleteEvent(URI.create(SyncID), androidEvent.getETag())) { String mSelectionClause = "(" + Events._ID + "= ?)"; String[] mSelectionArgs = { String.valueOf(EventID) }; int countDeleted = provider.delete( asSyncAdapter(Events.CONTENT_URI, account.name, account.type), mSelectionClause, mSelectionArgs); if (countDeleted == 1) { rowDelete += 1; notifyList.add(androidEvent.getUri()); } } } else { //update the android event to the server String uid = androidEvent.getUID(); if ((uid == null) || (uid.equals(""))) { //COMPAT: this is needed because in the past, the UID was not stored in the android event CalendarEvent calendarEvent = new CalendarEvent(account, provider); URI syncURI = new URI(SyncID); calendarEvent.setUri(syncURI); calendarEvent.calendarURL = caldavCalendarUri.toURL(); if (calendarEvent.fetchBody()) { calendarEvent.readContentValues(); uid = calendarEvent.getUID(); } } if (uid != null) { androidEvent.createIcs(uid); if (facade.updateEvent(URI.create(SyncID), androidEvent.getIcsEvent().toString(), androidEvent.getETag())) { selection = "(" + Events._ID + "= ?)"; selectionArgs = new String[] { EventID.toString() }; androidEvent.ContentValues.put(Events.DIRTY, 0); //google doesn't send the etag after update String LastETag = facade.getLastETag(); if (!LastETag.equals("")) { androidEvent.ContentValues.put(Event.ETAG, LastETag); } else { //so get the etag with a new REPORT CalendarEvent calendarEvent = new CalendarEvent(account, provider); calendarEvent.calendarURL = caldavCalendarUri.toURL(); URI SyncURI = new URI(SyncID); calendarEvent.setUri(SyncURI); CaldavFacade.getEvent(calendarEvent); androidEvent.ContentValues.put(Event.ETAG, calendarEvent.getETag()); } androidEvent.ContentValues.put(Event.RAWDATA, androidEvent.getIcsEvent().toString()); int RowCount = provider.update( asSyncAdapter(androidEvent.getUri(), account.name, account.type), androidEvent.ContentValues, null, null); if (RowCount == 1) { rowUpdate += 1; notifyList.add(androidEvent.getUri()); } } else { rowDirty += 1; } } else { rowDirty += 1; } } } curEvent.close(); /*if ((rowInsert > 0) || (rowUpdate > 0) || (rowDelete > 0) || (rowDirty > 0)) { Log.i(TAG,"Android Rows inserted: " + String.valueOf(rowInsert)); Log.i(TAG,"Android Rows updated: " + String.valueOf(rowUpdate)); Log.i(TAG,"Android Rows deleted: " + String.valueOf(rowDelete)); Log.i(TAG,"Android Rows dirty: " + String.valueOf(rowDirty)); }*/ stats.numInserts += rowInsert; stats.numUpdates += rowUpdate; stats.numDeletes += rowDelete; stats.numSkippedEntries += rowDirty; stats.numEntries += rowInsert + rowUpdate + rowDelete; } catch (RemoteException e) { e.printStackTrace(); } catch (URISyntaxException e) { // TODO Automatisch generierter Erfassungsblock e.printStackTrace(); } catch (ClientProtocolException e) { // TODO Automatisch generierter Erfassungsblock e.printStackTrace(); } catch (IOException e) { // TODO Automatisch generierter Erfassungsblock e.printStackTrace(); } catch (CaldavProtocolException e) { // TODO Automatisch generierter Erfassungsblock e.printStackTrace(); } catch (ParserException e) { // TODO Automatisch generierter Erfassungsblock e.printStackTrace(); } return rowDirty; }
From source file:de.unigoettingen.sub.commons.contentlib.servlet.controller.GetImageAction.java
/************************************************************************************ * exectute all image actions (rotation, scaling etc.) and send image back to output stream of the servlet, after setting correct mime type * //from w w w . j a va 2 s. co m * @param request {@link HttpServletRequest} of ServletRequest * @param response {@link HttpServletResponse} for writing to response output stream * @throws IOException * @throws ImageInterpreterException * @throws ServletException * @throws ContentLibException * @throws URISyntaxException * @throws ContentLibPdfException ************************************************************************************/ @Override public void run(ServletContext servletContext, HttpServletRequest request, HttpServletResponse response) throws IOException, URISyntaxException, ContentLibException { long startTime = System.currentTimeMillis(); super.run(servletContext, request, response); /* * -------------------------------- get central configuration -------------------------------- */ URI sourceImageUrl = null; ContentServerConfiguration config = ContentServerConfiguration.getInstance(); if (!request.getParameter("sourcepath").startsWith("file:") && !request.getParameter("sourcepath").startsWith("http:")) { sourceImageUrl = new URI(config.getRepositoryPathImages() + request.getParameter("sourcepath")); } else { sourceImageUrl = new URI(request.getParameter("sourcepath")); } try { Cache cc = null; ServletOutputStream output = response.getOutputStream(); if (request.getParameter("thumbnail") != null) { cc = ContentServer.getThumbnailCache(); } else { cc = ContentServer.getContentCache(); } // String myUniqueID = getContentCacheIdForRequest(request, config); String myUniqueID = getContentCacheIdForParamMap(request.getParameterMap(), config); String targetExtension = request.getParameter("format"); boolean ignoreCache = false; /* check if cache should be ignored */ if (request.getParameter("ignoreCache") != null) { String ignore = request.getParameter("ignoreCache").trim(); ignoreCache = Boolean.parseBoolean(ignore); } boolean useCache = false; if (request.getParameter("thumbnail") != null) { useCache = config.getThumbnailCacheUse(); } else { useCache = config.getContentCacheUse(); } if (request.getParameterMap().containsKey("highlight")) { useCache = false; } if (cc == null || !useCache) { ignoreCache = true; cc = null; LOGGER.debug("cache deactivated via configuration"); } if (!ignoreCache && cc.isKeyInCache(myUniqueID + "." + targetExtension)) { LOGGER.debug("get file from cache: " + myUniqueID + "." + targetExtension); CacheObject co; try { co = (CacheObject) cc.get(myUniqueID + "." + targetExtension).getObjectValue(); ByteArrayInputStream in = new ByteArrayInputStream(co.getData()); byte[] buf = new byte[1024]; int len; while ((len = in.read(buf)) > 0) { output.write(buf, 0, len); } in.close(); output.flush(); output.close(); return; } catch (NullPointerException e) { LOGGER.debug("element not in cache anymore: " + myUniqueID + "." + targetExtension); } } else if (!ignoreCache) { LOGGER.debug("file not found in cache: " + myUniqueID + "." + targetExtension); } // if (!ignoreCache && cc.cacheContains(myUniqueID, targetExtension)) { // LOGGER.debug("get file from cache: " + myUniqueID); // cc.writeToStream(output, myUniqueID, targetExtension); // output.flush(); // output.close(); // return; // } else if (ignoreCache == false) { // LOGGER.debug("file not found in cache: " + myUniqueID); // } // /* // * -------------------------------- if there is an internal request from goobiContentServer, you have to overwrite the // sourcepath with // * given attribute for image url -------------------------------- // */ // if (request.getAttribute("sourcepath") != null) { // sourceImageUrl = new URI((String) request.getAttribute("sourcepath")); // } LOGGER.debug("source image:" + sourceImageUrl); /* * -------------------------------- retrieve source image from url -------------------------------- */ ImageManager sourcemanager = new ImageManager(sourceImageUrl.toURL()); LOGGER.trace("imageManager initialized"); /* * -------------------------------- set the defaults -------------------------------- */ int angle = 0; int scaleX = 100; int scaleY = 100; int scaleType = ImageManager.SCALE_BY_PERCENT; LinkedList<String> highlightCoordinateList = null; Color highlightColor = null; Watermark myWatermark = null; LOGGER.trace("Variables set"); /* * -------------------------------- rotate -------------------------------- */ if (request.getParameterMap().containsKey("rotate")) { angle = Integer.parseInt(request.getParameter("rotate")); LOGGER.trace("rotate image:" + angle); } /* * -------------------------------- scale: scale the image to some percent value -------------------------------- */ if (request.getParameterMap().containsKey("scale")) { scaleX = Integer.parseInt(request.getParameter("scale")); scaleY = scaleX; scaleType = ImageManager.SCALE_BY_PERCENT; LOGGER.trace("scale image to percent:" + scaleX); } if (request.getParameterMap().containsKey("width") && request.getParameterMap().containsKey("height")) { scaleX = Integer.parseInt(request.getParameter("width")); scaleY = Integer.parseInt(request.getParameter("height")); scaleType = ImageManager.SCALE_TO_BOX; } /* * -------------------------------- width: scale image to fixed width -------------------------------- */ else if (request.getParameterMap().containsKey("width")) { scaleX = Integer.parseInt(request.getParameter("width")); scaleY = 0; scaleType = ImageManager.SCALE_BY_WIDTH; LOGGER.trace("scale image to width:" + scaleX); } /* * -------------------------------- height: scale image to fixed height -------------------------------- */ else if (request.getParameterMap().containsKey("height")) { scaleY = Integer.parseInt(request.getParameter("height")); scaleX = 0; scaleType = ImageManager.SCALE_BY_HEIGHT; LOGGER.trace("scale image to height:" + scaleY); } /* * -------------------------------- highlight -------------------------------- */ if (request.getParameterMap().containsKey("highlight")) { highlightCoordinateList = new LinkedList<String>(); String highlight = request.getParameter("highlight"); StrTokenizer areas = new StrTokenizer(highlight, "$"); for (String area : areas.getTokenArray()) { StrTokenizer coordinates = new StrTokenizer(area, ","); highlightCoordinateList.add(coordinates.getContent()); } highlightColor = config.getDefaultHighlightColor(); } /* * -------------------------------- insert watermark, if it should be used -------------------------------- */ if (!request.getParameterMap().containsKey("ignoreWatermark") && config.getWatermarkUse()) { File watermarkfile = new File(new URI(config.getWatermarkConfigFilePath())); myWatermark = Watermark.generateWatermark(request, watermarkfile); } /* * -------------------------------- prepare target -------------------------------- */ // change to true if watermark should scale RenderedImage targetImage = null; if (config.getScaleWatermark()) { targetImage = sourcemanager.scaleImageByPixel(scaleX, scaleY, scaleType, angle, highlightCoordinateList, highlightColor, myWatermark, true, ImageManager.BOTTOM); } else { targetImage = sourcemanager.scaleImageByPixel(scaleX, scaleY, scaleType, angle, highlightCoordinateList, highlightColor, myWatermark, false, ImageManager.BOTTOM); } LOGGER.trace("Creating ImageInterpreter"); ImageFileFormat targetFormat = ImageFileFormat.getImageFileFormatFromFileExtension(targetExtension); ImageInterpreter wi = targetFormat.getInterpreter(targetImage); // read file LOGGER.trace("Image stored in " + wi.getClass().toString()); /* * -------------------------------- set file name and attachment header from parameter or from configuration * -------------------------------- */ LOGGER.trace("Creating target file"); StringBuilder targetFileName = new StringBuilder(); if (config.getSendImageAsAttachment()) { targetFileName.append("attachment; "); } targetFileName.append("filename="); if (request.getParameter("targetFileName") != null) { targetFileName.append(request.getParameter("targetFileName")); } else { String filename = ContentLibUtil.getCustomizedFileName(config.getDefaultFileNameImages(), "." + targetFormat.getFileExtension()); targetFileName.append(filename); } LOGGER.trace("Adding targetFile " + targetFileName.toString() + " to response"); response.setHeader("Content-Disposition", targetFileName.toString()); response.setContentType(targetFormat.getMimeType()); /* * -------------------------------- resolution -------------------------------- */ LOGGER.trace("Setting image resolution values"); if (request.getParameter("resolution") != null) { wi.setXResolution(Float.parseFloat(request.getParameter("resolution"))); wi.setYResolution(Float.parseFloat(request.getParameter("resolution"))); } else { wi.setXResolution(config.getDefaultResolution()); wi.setYResolution(config.getDefaultResolution()); } LOGGER.trace("Setting image compression"); if (request.getParameter("compression") != null) { String value = request.getParameter("compression"); try { int intvalue = Integer.parseInt(value); wi.setWriterCompressionValue(intvalue); } catch (Exception e) { LOGGER.trace("value is not a number, use default value"); } } /* * -------------------------------- write target image to stream -------------------------------- */ // cc.put(new Element(myUniqueID + "." + targetExtension, wi.getRenderedImage())); if (cc != null) { byte[] data = wi.writeToStreamAndByteArray(output); cc.putIfAbsent(new Element(myUniqueID + "." + targetExtension, new CacheObject(data))); } else { LOGGER.trace("writing file to servlet response"); wi.writeToStream(null, output); } LOGGER.trace("Done writing ImageInterpreter to stream"); wi.clear(); LOGGER.trace("Done clearing ImageInterpreter"); } catch (Exception e) { LOGGER.error("CacheException", e); } long endTime = System.currentTimeMillis(); LOGGER.trace("Content server time to process request: " + (endTime - startTime) + " ms"); // try { // CommonUtils.appendTextFile("Image request for file " + new File(sourceImageUrl).getAbsolutePath() + "; Time to process: " + (endTime - // startTime) // + " ms\n", new File(de.unigoettingen.sub.commons.contentlib.servlet.Util.getBaseFolderAsFile(), "timeConsumptionLog.txt")); // // } catch (IOException e) { // LOGGER.info("Unable to write time log file due to IOException " + e.toString()); // } }
From source file:org.apache.maven.plugin.javadoc.AbstractJavadocMojo.java
/** * @param link not null/*from w ww . j ava2 s. c o m*/ * @return <code>true</code> if the link has a <code>/package-list</code>, <code>false</code> otherwise. * @see <a href="http://docs.oracle.com/javase/1.4.2/docs/tooldocs/solaris/javadoc.html#package-list"> * package-list spec</a> * @since 2.6 */ private boolean isValidJavadocLink(String link) { try { URI linkUri; if (link.trim().toLowerCase(Locale.ENGLISH).startsWith("http:") || link.trim().toLowerCase(Locale.ENGLISH).startsWith("https:") || link.trim().toLowerCase(Locale.ENGLISH).startsWith("ftp:") || link.trim().toLowerCase(Locale.ENGLISH).startsWith("file:")) { linkUri = new URI(link + "/package-list"); } else { // links can be relative paths or files File dir = new File(link); if (!dir.isAbsolute()) { dir = new File(getOutputDirectory(), link); } if (!dir.isDirectory()) { getLog().error("The given File link: " + dir + " is not a dir."); } linkUri = new File(dir, "package-list").toURI(); } if (!JavadocUtil.isValidPackageList(linkUri.toURL(), settings, validateLinks)) { if (getLog().isErrorEnabled()) { getLog().error("Invalid link: " + link + "/package-list. Ignored it."); } return false; } return true; } catch (URISyntaxException e) { if (getLog().isErrorEnabled()) { getLog().error("Malformed link: " + link + "/package-list. Ignored it."); } return false; } catch (IOException e) { if (getLog().isErrorEnabled()) { getLog().error("Error fetching link: " + link + "/package-list. Ignored it."); } return false; } }
From source file:fr.cls.atoll.motu.library.misc.intfce.Organizer.java
/** * Open connection./* ww w. jav a 2 s .co m*/ * * @param uri the uri * @return the uRL connection * @throws MotuException the motu exception */ public static URLConnection openConnection(URI uri) throws MotuException { if (LOG.isDebugEnabled()) { LOG.debug("openConnection(URI) - start"); } try { URLConnection returnURLConnection = Organizer.openConnection(uri.toURL()); if (LOG.isDebugEnabled()) { LOG.debug("openConnection(URI) - end"); } return returnURLConnection; } catch (MalformedURLException e) { LOG.error("openConnection(URI)", e); throw new MotuException(String.format("Unable to convert uri '%s' to URL object ", uri), e); } }