List of usage examples for java.net URI resolve
public URI resolve(String str)
From source file:org.kitodo.production.services.data.ProcessService.java
/** * Download images.//from w w w. j a v a 2s . com * * @param process * process object * @param userHome * save file * @param atsPpnBand * String * @param directorySuffix * String */ public void downloadImages(Process process, URI userHome, String atsPpnBand, final String directorySuffix) throws IOException { Project project = process.getProject(); // determine the output path URI tifDirectory = getImagesTifDirectory(true, process.getId(), process.getTitle(), process.getProcessBaseUri()); // copy the source folder to the destination folder if (fileService.fileExist(tifDirectory) && !fileService.getSubUris(tifDirectory).isEmpty()) { URI destination = userHome.resolve(File.separator + atsPpnBand + directorySuffix); // with Agora import simply create the folder if (project.isUseDmsImport()) { if (!fileService.fileExist(destination)) { fileService.createDirectory(userHome, atsPpnBand + directorySuffix); } } else { // if no Agora import, then create again the folder with user authorization User user = ServiceManager.getUserService().getAuthenticatedUser(); try { fileService.createDirectoryForUser(destination, user.getLogin()); } catch (RuntimeException e) { Helper.setErrorMessage(ERROR_EXPORT, "could not create destination directory", logger, e); } } copyProcessFiles(tifDirectory, destination, ImageHelper.dataFilter); } }
From source file:org.kitodo.services.data.ProcessService.java
/** * DMS-Export an eine gewnschte Stelle./* w w w . j a v a 2s.c o m*/ * * @param process * object */ public boolean startDmsExport(Process process, boolean exportWithImages, boolean exportFullText) throws IOException, PreferencesException, org.apache.commons.configuration.ConfigurationException, WriteException { Prefs preferences = serviceManager.getRulesetService().getPreferences(process.getRuleset()); Project project = process.getProject(); ConfigProjects configProjects = new ConfigProjects(project.getTitle()); String atsPpnBand = process.getTitle(); /* * Dokument einlesen */ Fileformat gdzfile; Fileformat newfile; FolderInformation fi = new FolderInformation(process.getId(), process.getTitle()); try { URI metadataPath = fi.getMetadataFilePath(); gdzfile = readMetadataFile(metadataPath, preferences); switch (MetadataFormat.findFileFormatsHelperByName(project.getFileFormatDmsExport())) { case METS: newfile = new MetsModsImportExport(preferences); break; case METS_AND_RDF: default: newfile = new RDFFile(preferences); break; } newfile.setDigitalDocument(gdzfile.getDigitalDocument()); gdzfile = newfile; } catch (Exception e) { Helper.setFehlerMeldung(Helper.getTranslation("exportError") + process.getTitle(), e); logger.error("Export abgebrochen, xml-LeseFehler", e); return false; } String rules = ConfigCore.getParameter("copyData.onExport"); if (rules != null && !rules.equals("- keine Konfiguration gefunden -")) { try { new DataCopier(rules).process(new CopierData(newfile, process)); } catch (ConfigurationException e) { Helper.setFehlerMeldung("dataCopier.syntaxError", e.getMessage()); return false; } catch (RuntimeException e) { Helper.setFehlerMeldung("dataCopier.runtimeException", e.getMessage()); return false; } } trimAllMetadata(gdzfile.getDigitalDocument().getLogicalDocStruct()); /* * Metadaten validieren */ if (ConfigCore.getBooleanParameter("useMetadatenvalidierung")) { MetadatenVerifizierung mv = new MetadatenVerifizierung(); if (!mv.validate(gdzfile, preferences, process)) { return false; } } /* * Speicherort vorbereiten und downloaden */ URI zielVerzeichnis; URI benutzerHome; zielVerzeichnis = new File(project.getDmsImportImagesPath()).toURI(); benutzerHome = zielVerzeichnis; /* ggf. noch einen Vorgangsordner anlegen */ if (project.isDmsImportCreateProcessFolder()) { zielVerzeichnis = benutzerHome.resolve(File.separator + process.getTitle()); /* alte Import-Ordner lschen */ if (!fileService.delete(benutzerHome)) { Helper.setFehlerMeldung("Export canceled, Process: " + process.getTitle(), "Import folder could not be cleared"); return false; } /* alte Success-Ordner lschen */ File successFile = new File(project.getDmsImportSuccessPath() + File.separator + process.getTitle()); if (!fileService.delete(successFile.toURI())) { Helper.setFehlerMeldung("Export canceled, Process: " + process.getTitle(), "Success folder could not be cleared"); return false; } /* alte Error-Ordner lschen */ File errorfile = new File(project.getDmsImportErrorPath() + File.separator + process.getTitle()); if (!fileService.delete(errorfile.toURI())) { Helper.setFehlerMeldung("Export canceled, Process: " + process.getTitle(), "Error folder could not be cleared"); return false; } if (!fileService.fileExist(benutzerHome)) { fileService.createDirectory(benutzerHome, File.separator + process.getTitle()); } } /* * der eigentliche Download der Images */ try { if (exportWithImages) { imageDownload(process, benutzerHome, atsPpnBand, DIRECTORY_SUFFIX, fi); fulltextDownload(benutzerHome, atsPpnBand, fi); } else if (exportFullText) { fulltextDownload(benutzerHome, atsPpnBand, fi); } directoryDownload(process, zielVerzeichnis); } catch (Exception e) { Helper.setFehlerMeldung("Export canceled, Process: " + process.getTitle(), e); return false; } /* * zum Schluss Datei an gewnschten Ort exportieren entweder direkt in * den Import-Ordner oder ins Benutzerhome anschliessend den * Import-Thread starten */ if (project.isUseDmsImport()) { if (MetadataFormat .findFileFormatsHelperByName(project.getFileFormatDmsExport()) == MetadataFormat.METS) { /* Wenn METS, dann per writeMetsFile schreiben... */ writeMetsFile(process, benutzerHome + File.separator + atsPpnBand + ".xml", gdzfile, false); } else { /* ...wenn nicht, nur ein Fileformat schreiben. */ gdzfile.write(benutzerHome + File.separator + atsPpnBand + ".xml"); } /* ggf. sollen im Export mets und rdf geschrieben werden */ if (MetadataFormat .findFileFormatsHelperByName(project.getFileFormatDmsExport()) == MetadataFormat.METS_AND_RDF) { writeMetsFile(process, benutzerHome + File.separator + atsPpnBand + ".mets.xml", gdzfile, false); } Helper.setMeldung(null, process.getTitle() + ": ", "DMS-Export started"); if (!ConfigCore.getBooleanParameter("exportWithoutTimeLimit")) { /* Success-Ordner wieder lschen */ if (project.isDmsImportCreateProcessFolder()) { File successFile = new File( project.getDmsImportSuccessPath() + File.separator + process.getTitle()); fileService.delete(successFile.toURI()); } } } return true; }
From source file:org.openremote.controller.service.Deployer.java
/** * Extracts an OpenRemote deployment archive into a given target file directory. * * @param inputStream Input stream for reading the ZIP archive. Note that this method will * attempt to close the stream on exiting. * * @param targetDir URI that points to the root directory where the extracted files should * be placed. Note that the URI must be an absolute file URI. * * @throws ConfigurationException If target file URI cannot be resolved, or if the target * file path does not exist * * @throws IOException If there was an unrecovable I/O error reading or extracting * the ZIP archive. Note that errors on individual files within * the archive may not generate exceptions but be logged as * errors or warnings instead. *///from w ww . ja v a2 s .co m private void unzip(InputStream inputStream, URI targetDir) throws ConfigurationException, IOException { if (targetDir == null || targetDir.getPath().equals("") || !targetDir.isAbsolute()) { throw new ConfigurationException( "Target dir must be absolute file: protocol URI, got '" + targetDir + +'.'); } File checkedTargetDir = new File(targetDir); if (!checkedTargetDir.exists()) { throw new ConfigurationException("The path ''{0}'' doesn't exist.", targetDir); } ZipInputStream zipInputStream = new ZipInputStream(new BufferedInputStream(inputStream)); ZipEntry zipEntry = null; BufferedOutputStream fileOutputStream = null; try { while ((zipEntry = zipInputStream.getNextEntry()) != null) { if (zipEntry.isDirectory()) { continue; } try { URI extractFileURI = targetDir.resolve(new URI(null, null, zipEntry.getName(), null)); log.debug("Resolved URI to ''{0}''", extractFileURI); File zippedFile = new File(extractFileURI); log.debug("Attempting to extract ''{0}'' to ''{1}''.", zipEntry, zippedFile); try { fileOutputStream = new BufferedOutputStream(new FileOutputStream(zippedFile)); int b; while ((b = zipInputStream.read()) != -1) { fileOutputStream.write(b); } } catch (FileNotFoundException e) { log.error("Could not extract ''{0}'' -- file ''{1}'' could not be created : {2}", e, zipEntry.getName(), zippedFile, e.getMessage()); } catch (IOException e) { log.warn("Zip extraction of ''{0}'' to ''{1}'' failed : {2}", e, zipEntry, zippedFile, e.getMessage()); } finally { if (fileOutputStream != null) { try { fileOutputStream.close(); log.debug("Extraction of ''{0}'' to ''{1}'' completed.", zipEntry, zippedFile); } catch (Throwable t) { log.warn("Failed to close file ''{0}'' : {1}", t, zippedFile, t.getMessage()); } } if (zipInputStream != null) { if (zipEntry != null) { try { zipInputStream.closeEntry(); } catch (IOException e) { log.warn("Failed to close ZIP file entry ''{0}'' : {1}", e, zipEntry, e.getMessage()); } } } } } catch (URISyntaxException e) { log.warn("Cannot extract {0} from zip : {1}", e, zipEntry, e.getMessage()); } } } finally { try { if (zipInputStream != null) { zipInputStream.close(); } } catch (IOException e) { log.warn("Failed to close zip file : {0}", e, e.getMessage()); } if (fileOutputStream != null) { try { fileOutputStream.close(); } catch (IOException e) { log.warn("Failed to close file : {0}", e, e.getMessage()); } } } }
From source file:io.swagger.v3.parser.util.OpenAPIDeserializer.java
public Server getServer(ObjectNode obj, String location, ParseResult result, String path) { if (obj == null) { return null; }//ww w. j ava 2 s . co m Server server = new Server(); String value = getString("url", obj, true, location, result); if (StringUtils.isNotBlank(value)) { if (!isValidURL(value) && path != null) { try { final URI absURI = new URI(path); if ("http".equals(absURI.getScheme()) || "https".equals(absURI.getScheme())) { value = absURI.resolve(new URI(value)).toString(); } } catch (URISyntaxException e) { e.printStackTrace(); } } server.setUrl(value); } value = getString("description", obj, false, location, result); if (StringUtils.isNotBlank(value)) { server.setDescription(value); } if (obj.get("variables") != null) { ObjectNode variables = getObject("variables", obj, false, location, result); ServerVariables serverVariables = getServerVariables(variables, String.format("%s.%s", location, "variables"), result); if (serverVariables != null && serverVariables.size() > 0) { server.setVariables(serverVariables); } } Map<String, Object> extensions = getExtensions(obj); if (extensions != null && extensions.size() > 0) { server.setExtensions(extensions); } Set<String> keys = getKeys(obj); for (String key : keys) { if (!SERVER_KEYS.contains(key) && !key.startsWith("x-")) { result.extra(location, key, obj.get(key)); } } return server; }
From source file:org.apache.cxf.transport.http.asyncclient.AsyncHTTPConduit.java
@Override protected void setupConnection(Message message, Address address, HTTPClientPolicy csPolicy) throws IOException { if (factory.isShutdown()) { message.put(USE_ASYNC, Boolean.FALSE); super.setupConnection(message, address, csPolicy); return;/* w w w . ja va 2 s . co m*/ } boolean addressChanged = false; // need to do some clean up work on the URI address URI uri = address.getURI(); String uriString = uri.toString(); if (uriString.startsWith("hc://")) { try { uriString = uriString.substring(5); uri = new URI(uriString); addressChanged = true; } catch (URISyntaxException ex) { throw new MalformedURLException("unsupport uri: " + uriString); } } String s = uri.getScheme(); if (!"http".equals(s) && !"https".equals(s)) { throw new MalformedURLException("unknown protocol: " + s); } Object o = message.getContextualProperty(USE_ASYNC); if (o == null) { o = factory.getUseAsyncPolicy(); } switch (UseAsyncPolicy.getPolicy(o)) { case ALWAYS: o = true; break; case NEVER: o = false; break; case ASYNC_ONLY: default: o = !message.getExchange().isSynchronous(); break; } // check tlsClientParameters from message header TLSClientParameters clientParameters = message.get(TLSClientParameters.class); if (clientParameters == null) { clientParameters = tlsClientParameters; } if (uri.getScheme().equals("https") && clientParameters != null && clientParameters.getSSLSocketFactory() != null) { //if they configured in an SSLSocketFactory, we cannot do anything //with it as the NIO based transport cannot use socket created from //the SSLSocketFactory. o = false; } if (!MessageUtils.isTrue(o)) { message.put(USE_ASYNC, Boolean.FALSE); super.setupConnection(message, addressChanged ? new Address(uriString, uri) : address, csPolicy); return; } if (StringUtils.isEmpty(uri.getPath())) { //hc needs to have the path be "/" uri = uri.resolve("/"); addressChanged = true; } message.put(USE_ASYNC, Boolean.TRUE); if (LOG.isLoggable(Level.FINE)) { LOG.fine("Asynchronous connection to " + uri.toString() + " has been set up"); } message.put("http.scheme", uri.getScheme()); String httpRequestMethod = (String) message.get(Message.HTTP_REQUEST_METHOD); if (httpRequestMethod == null) { httpRequestMethod = "POST"; message.put(Message.HTTP_REQUEST_METHOD, httpRequestMethod); } final CXFHttpRequest e = new CXFHttpRequest(httpRequestMethod); BasicHttpEntity entity = new BasicHttpEntity() { public boolean isRepeatable() { return e.getOutputStream().retransmitable(); } }; entity.setChunked(true); entity.setContentType((String) message.get(Message.CONTENT_TYPE)); e.setURI(uri); e.setEntity(entity); RequestConfig.Builder b = RequestConfig.custom().setConnectTimeout((int) csPolicy.getConnectionTimeout()) .setSocketTimeout((int) csPolicy.getReceiveTimeout()) .setConnectionRequestTimeout((int) csPolicy.getReceiveTimeout()); Proxy p = proxyFactory.createProxy(csPolicy, uri); if (p != null && p.type() != Proxy.Type.DIRECT) { InetSocketAddress isa = (InetSocketAddress) p.address(); HttpHost proxy = new HttpHost(isa.getHostName(), isa.getPort()); b.setProxy(proxy); } e.setConfig(b.build()); message.put(CXFHttpRequest.class, e); }
From source file:org.kitodo.production.services.data.ProcessService.java
private void downloadOCR(Process process, URI userHome, String atsPpnBand) throws IOException { URI ocr = fileService.getOcrDirectory(process); if (fileService.fileExist(ocr)) { List<URI> directories = fileService.getSubUris(ocr); for (URI directory : directories) { if (fileService.isDirectory(directory) && !fileService.getSubUris(directory).isEmpty() && fileService.getFileName(directory).contains("_")) { String suffix = fileService.getFileNameWithExtension(directory) .substring(fileService.getFileNameWithExtension(directory).lastIndexOf('_')); URI destination = userHome.resolve(File.separator + atsPpnBand + suffix); if (!fileService.fileExist(destination)) { fileService.createDirectory(userHome, atsPpnBand + suffix); }/*from w w w. j av a 2 s. c o m*/ copyProcessFiles(directory, destination, null); } } } }
From source file:org.kitodo.services.data.ProcessService.java
/** * Download image.//ww w. j a va 2 s .c o m * * @param process * process object * @param userHome * safe file * @param atsPpnBand * String * @param ordnerEndung * String */ public void imageDownload(Process process, URI userHome, String atsPpnBand, final String ordnerEndung, FolderInformation fi) throws IOException { Project project = process.getProject(); /* * den Ausgangspfad ermitteln */ URI tifOrdner = fi.getImagesTifDirectory(true); /* * jetzt die Ausgangsordner in die Zielordner kopieren */ if (fileService.fileExist(tifOrdner) && fileService.getSubUris(tifOrdner).size() > 0) { URI zielTif = userHome.resolve(File.separator + atsPpnBand + ordnerEndung); /* bei Agora-Import einfach den Ordner anlegen */ if (project.isUseDmsImport()) { if (!fileService.fileExist(zielTif)) { fileService.createDirectory(userHome, atsPpnBand + ordnerEndung); } } else { /* * wenn kein Agora-Import, dann den Ordner mit * Benutzerberechtigung neu anlegen */ User myUser = (User) Helper.getManagedBeanValue("#{LoginForm.myBenutzer}"); try { fileService.createDirectoryForUser(zielTif, myUser.getLogin()); } catch (Exception e) { Helper.setFehlerMeldung("Export canceled, error", "could not create destination directory"); logger.error("could not create destination directory", e); } } /* jetzt den eigentlichen Kopiervorgang */ ArrayList<URI> dateien = fileService.getSubUris(Helper.dataFilter, tifOrdner); for (URI file : dateien) { if (fileService.isFile(file)) { URI target = zielTif.resolve(File.separator + fileService.getFileNameWithExtension(file)); fileService.copyFile(file, target); } } } }
From source file:org.opencb.opencga.storage.core.manager.variant.operations.VariantStatsStorageOperation.java
public void calculateStats(long studyId, List<String> cohorts, String outdirStr, QueryOptions options, String sessionId) throws CatalogException, IOException, URISyntaxException, StorageEngineException { Job.Type step = Job.Type.COHORT_STATS; String fileIdStr = options.getString(Options.FILE_ID.key(), null); boolean overwriteStats = options.getBoolean(Options.OVERWRITE_STATS.key(), false); boolean updateStats = options.getBoolean(Options.UPDATE_STATS.key(), false); boolean resume = options.getBoolean(Options.RESUME.key(), Options.RESUME.defaultValue()); final Long fileId = fileIdStr == null ? null : catalogManager.getFileId(fileIdStr, Long.toString(studyId), sessionId); // Outdir must be empty URI outdirUri = UriUtils.createDirectoryUri(outdirStr); final Path outdir = Paths.get(outdirUri); outdirMustBeEmpty(outdir, options);/*from w w w . j a v a 2 s . c om*/ Aggregation aggregation = getAggregation(studyId, options, sessionId); List<Long> cohortIds = checkCohorts(studyId, aggregation, cohorts, options, sessionId); Map<Long, Cohort> cohortsMap = checkCanCalculateCohorts(studyId, cohortIds, updateStats, resume, sessionId); String region = options.getString(VariantDBAdaptor.VariantQueryParams.REGION.key()); String outputFileName = buildOutputFileName(cohortIds, options, cohortsMap, region); Long catalogOutDirId = getCatalogOutdirId(studyId, options, sessionId); QueryOptions calculateStatsOptions = new QueryOptions(options) // .append(VariantStorageEngine.Options.LOAD_BATCH_SIZE.key(), 100) // .append(VariantStorageEngine.Options.LOAD_THREADS.key(), 6) .append(Options.OVERWRITE_STATS.key(), overwriteStats) .append(Options.UPDATE_STATS.key(), updateStats).append(Options.RESUME.key(), resume); calculateStatsOptions.putIfNotNull(Options.FILE_ID.key(), fileId); calculateStatsOptions.putIfNotEmpty(VariantDBAdaptor.VariantQueryParams.REGION.key(), region); // if the study is aggregated and a mapping file is provided, pass it to storage // and create in catalog the cohorts described in the mapping file String aggregationMappingFile = options.getString(Options.AGGREGATION_MAPPING_PROPERTIES.key()); if (Aggregation.isAggregated(aggregation) && StringUtils.isNotEmpty(aggregationMappingFile)) { Properties mappingFile = readAggregationMappingFile(aggregationMappingFile); calculateStatsOptions.append(Options.AGGREGATION_MAPPING_PROPERTIES.key(), mappingFile); } DataStore dataStore = StorageOperation.getDataStore(catalogManager, studyId, File.Bioformat.VARIANT, sessionId); StudyConfiguration studyConfiguration = updateStudyConfiguration(sessionId, studyId, dataStore); Thread hook = buildHook(cohortIds, sessionId, outdir); writeJobStatus(outdir, new Job.JobStatus(Job.JobStatus.RUNNING, "Job has just started")); Runtime.getRuntime().addShutdownHook(hook); // Up to this point, catalog has not been modified try { // Modify cohort status to "CALCULATING" updateCohorts(cohortIds, sessionId, Cohort.CohortStatus.CALCULATING, "Start calculating stats"); calculateStatsOptions.put(DefaultVariantStatisticsManager.OUTPUT, outdirUri.resolve(outputFileName)); VariantStorageEngine variantStorageEngine = storageEngineFactory .getVariantStorageEngine(dataStore.getStorageEngine()); List<String> cohortsName = cohortsMap.values().stream().map(Cohort::getName) .collect(Collectors.toList()); variantStorageEngine.calculateStats(studyConfiguration.getStudyName(), cohortsName, dataStore.getDbName(), calculateStatsOptions); // DefaultVariantStatisticsManager variantStatisticsManager = new DefaultVariantStatisticsManager(dbAdaptor); // // VariantDBAdaptor dbAdaptor = variantStorageManager.getDBAdaptor(dataStore.getDbName()); // Map<String, Integer> cohortNameIdMap = new HashMap<>(cohortIds.size()); // Map<String, Set<String>> cohortSamplesMap = new HashMap<>(cohortIds.size()); // for (Map.Entry<Long, Cohort> entry : cohortsMap.entrySet()) { // cohortNameIdMap.put(entry.getValue().getName(), entry.getKey().intValue()); // cohortSamplesMap.put(entry.getValue().getName(), entry.getValue().getSamples() // .stream() // .map(sampleId -> { // return studyConfiguration.getSampleIds().inverse().get(sampleId.intValue()); // }) // .collect(Collectors.toSet())); // } // URI stats = variantStatisticsManager.createStats(dbAdaptor, outdirUri.resolve(outputFileName), cohortSamplesMap, // cohortNameIdMap, studyConfiguration, calculateStatsOptions); // // writeJobStatus(outdir, new Job.JobStatus(Job.JobStatus.RUNNING, "Job still running. Statistics created.")); // variantStatisticsManager.loadStats(dbAdaptor, stats, studyConfiguration, options); if (catalogOutDirId != null) { copyResults(Paths.get(outdirUri), catalogOutDirId, sessionId); } writeJobStatus(outdir, new Job.JobStatus(Job.JobStatus.DONE, "Job completed")); // Modify cohort status to "READY" updateCohorts(cohortIds, sessionId, Cohort.CohortStatus.READY, ""); } catch (Exception e) { // Error! logger.error("Error executing stats. Set cohorts status to " + Cohort.CohortStatus.INVALID, e); writeJobStatus(outdir, new Job.JobStatus(Job.JobStatus.ERROR, "Job with error : " + e.getMessage())); // Modify to "INVALID" updateCohorts(cohortIds, sessionId, Cohort.CohortStatus.INVALID, "Error calculating stats: " + e.getMessage()); throw new StorageEngineException("Error calculating statistics.", e); } finally { // Remove hook Runtime.getRuntime().removeShutdownHook(hook); } }
From source file:tufts.vue.URLResource.java
@Override public void restoreRelativeTo(URI root) { // Even if the existing original resource exists, we always // choose the relative / "local" version, if it can be found. String relative = getProperty(FILE_RELATIVE_OLD); if (relative == null) { relative = getProperty(FILE_RELATIVE); if (relative == null) { // attempt to find us in case we're relative anyway: //recordRelativeTo(root); return; // nothing to do }/*from w w w . j a v a2 s . co m*/ } else { removeProperty(FILE_RELATIVE_OLD); setProperty(FILE_RELATIVE, relative); } final URI relativeURI = rebuildURI(relative); final URI absoluteURI = root.resolve(relativeURI); if (DEBUG.RESOURCE) { System.out.print(TERM_PURPLE); Resource.dumpURI(absoluteURI, "resolved absolute:"); Resource.dumpURI(relativeURI, "from relative:"); System.out.print(TERM_CLEAR); } if (absoluteURI != null) { final File file = new File(absoluteURI); if (file.canRead()) { // only change the spec if we can actually find the file (todo: test Vista -- does canRead work?) if (DEBUG.RESOURCE) setDebugProperty("relative URI", relativeURI); Log.info(TERM_PURPLE + "resolved " + relativeURI.getPath() + " to: " + file + TERM_CLEAR); setRelativeURI(relativeURI); setSpecByFile(file); } else { out_warn(TERM_RED + "can't find data relative to " + root + " at " + relative + "; can't read " + file + TERM_CLEAR); // todo: should probably delete the relative property key/value at this point } } else { out_error("failed to find relative " + relative + "; in " + root + " for " + this); } }
From source file:org.apache.ode.bpel.compiler.v2.WSDLRegistry.java
/** * Adds a WSDL definition for use in resolving MessageType, PortType, * Operation and BPEL properties and property aliases * * @param def WSDL definition//from w w w. j ava 2 s . co m */ @SuppressWarnings("unchecked") public void addDefinition(Definition4BPEL def, ResourceFinder rf, URI defuri) throws CompilationException { if (def == null) throw new NullPointerException("def=null"); if (__log.isDebugEnabled()) { __log.debug("addDefinition(" + def.getTargetNamespace() + " from " + def.getDocumentBaseURI() + ")"); } if (_definitions.containsKey(def.getTargetNamespace())) { // This indicates that we imported a WSDL with the same namespace from // two different locations. This is not an error, but should be a warning. if (__log.isInfoEnabled()) { __log.info("WSDL at " + defuri + " is a duplicate import, your documents " + "should all be in different namespaces (its's not nice but will still work)."); } } ArrayList<Definition4BPEL> defs; if (_definitions.get(def.getTargetNamespace()) == null) defs = new ArrayList<Definition4BPEL>(); else defs = _definitions.get(def.getTargetNamespace()); defs.add(def); _definitions.put(def.getTargetNamespace(), defs); captureSchemas(def, rf, defuri); if (__log.isDebugEnabled()) __log.debug("Processing <imports> in " + def.getDocumentBaseURI()); for (List<Import> imports : ((Map<String, List<Import>>) def.getImports()).values()) { HashSet<String> imported = new HashSet<String>(); for (Import im : imports) { // If there are several imports in the same WSDL all importing the same namespace // that is a sure sign of programmer error. if (imported.contains(im.getNamespaceURI())) { if (__log.isInfoEnabled()) { __log.info("WSDL at " + im.getLocationURI() + " imports several documents in the same " + "namespace (" + im.getNamespaceURI() + "), your documents should all be in different " + "namespaces (its's not nice but will still work)."); } } Definition4BPEL importDef = (Definition4BPEL) im.getDefinition(); // The assumption here is that if the definition is not set on the // import object then there was some problem parsing the thing, // although it would have been nice to actually get the parse // error. if (importDef == null) { CompilationException ce = new CompilationException( __cmsgs.errWsdlImportNotFound(im.getNamespaceURI(), im.getLocationURI()) .setSource(new SourceLocation(defuri))); if (_ctx == null) throw ce; _ctx.recoveredFromError(new SourceLocation(defuri), ce); continue; } imported.add(im.getNamespaceURI()); addDefinition((Definition4BPEL) im.getDefinition(), rf, defuri.resolve(im.getLocationURI())); } } }