public static String getResTxtContent(ClassLoader cl, String p) throws IOException { String s = res2txt_cont.get(p); if (s != null) return s; InputStream is = null; try { is = cl.getResourceAsStream(p); // is = this.getClass().getResourceAsStream(p); if (is == null) return null; byte[] buf = new byte[1024]; ByteArrayOutputStream baos = new ByteArrayOutputStream(); int len; while ((len = is.read(buf)) >= 0) { baos.write(buf, 0, len); } byte[] cont = baos.toByteArray(); s = new String(cont, "UTF-8"); res2txt_cont.put(p, s); return s; } finally { if (is != null) is.close(); } }
/** * Executes a query. * * @param query query to be executed * @return list of serialized result items * @throws IOException error during query execution */ private StringList execute(final WebDAVQuery query) throws IOException { final ClassLoader cl = getClass().getClassLoader(); final InputStream s = cl.getResourceAsStream(FILE); if (s == null) throw new IOException("WebDAV module not found"); final byte[] module = new IOStream(s).read(); final QueryProcessor qp = new QueryProcessor(query.toString(), http.context()); try { for (final Entry<String, Object> entry : query.entries()) { qp.bind(entry.getKey(), entry.getValue()); } qp.ctx.parseLibrary(string(module), FILE, qp.sc); final Result r = qp.execute(); final int n = (int) r.size(); final StringList items = new StringList(n); for (int i = 0; i < n; i++) { final ArrayOutput ao = new ArrayOutput(); r.serialize(Serializer.get(ao), 0); items.add(ao.toString()); } return items; } catch (final QueryException ex) { throw new BaseXException(ex); } catch (final Exception ex) { Util.debug(ex); throw new BaseXException(ex); } finally { qp.close(); } }
/** Copy one predefined Template from resources to a file. */ static void migrateTemplate(String template) throws IOException { File dir = TemplateDatabase.TemplateDir; File file = new File(dir, template); ClassLoader loader = TemplateDeployer.class.getClassLoader(); InputStream in = loader.getResourceAsStream("com/lightcrafts/templates/resources/" + template); if (in == null) { throw new IOException("Couldn't find resource for template " + template); } OutputStream out = new FileOutputStream(file); byte[] buffer = new byte[10000]; // bigger than any template try { int count; do { count = in.read(buffer); if (count > 0) { out.write(buffer, 0, count); } } while (count >= 0); } finally { try { out.close(); } catch (IOException e) { System.out.println("Failed to close template " + template); } } }
public String readFileFromJAR(String filepath) { String out = ""; try { // setup input buffer ClassLoader cl = this.getClass().getClassLoader(); InputStream instream = cl.getResourceAsStream(filepath); BufferedReader filereader = new BufferedReader(new InputStreamReader(instream)); // read lines String line = filereader.readLine(); while (line != null) { out += "\n" + line; line = filereader.readLine(); } filereader.close(); } catch (Exception e) { // e.printStackTrace(); } return out; }
@Override public String call(Integer i) throws Exception { ClassLoader ccl = Thread.currentThread().getContextClassLoader(); InputStream in = ccl.getResourceAsStream("test.resource"); byte[] bytes = ByteStreams.toByteArray(in); in.close(); return new String(bytes, 0, bytes.length, "UTF-8"); }
private void load(File jarFile) { ClassLoader loader; try { loader = URLClassLoader.newInstance( new URL[] {jarFile.toURI().toURL()}, getClass().getClassLoader()); } catch (MalformedURLException e) { Application.LOGGER.error( "Error while loading plugin file - " + jarFile.getAbsolutePath(), e); return; } InputStream stream = loader.getResourceAsStream(MANIFEST_FILE); Properties properties = new Properties(); try { properties.load(stream); } catch (IOException e) { Application.LOGGER.error( "Manifest file - " + MANIFEST_FILE + " not found in the plugin jar - " + jarFile.getAbsolutePath(), e); return; } String pluginClassName = properties.getProperty("plugin.class"); if (!properties.containsKey("plugin.class")) { Application.LOGGER.error( "plugin.class not defined in the manifest file in the plugin jar - " + jarFile.getAbsolutePath()); return; } Class<?> clazz; try { clazz = Class.forName(pluginClassName, true, loader); } catch (ClassNotFoundException e) { Application.LOGGER.error( "Plugin main class - " + pluginClassName + " defined in manifest not found in the plugin jar - " + jarFile.getAbsolutePath(), e); return; } if (!Plugin.class.isAssignableFrom(clazz)) { Application.LOGGER.error( "Plugin class - " + clazz + " is not a Plugin, in the plugin jar - " + jarFile.getAbsolutePath()); } load((Class<? extends Plugin>) clazz, properties); }
private static InputStream getAsInputStreamFromClassLoader(String filename) { ClassLoader cl = Thread.currentThread().getContextClassLoader(); InputStream is = cl == null ? null : cl.getResourceAsStream(filename); if (is == null) { // check system class loader is = XmlConfigurator.class.getClassLoader().getResourceAsStream(filename); } return is; }
/** * return a checker object which can be used to retrieve the super and interfaces of a class from * its name and classloader, identifying it from the Class instance if it the class is already * loaded otherwise loading the corresponding bytecode and parsing it to obtain the relevant * details. * * @param name the name of the superclass being checked * @param baseLoader the class loader of the subclass's bytecode * @return the requisite checker or null if the class does not need to be checked or cannot be * loaded */ public org.jboss.byteman.agent.check.ClassChecker getClassChecker( String name, ClassLoader baseLoader) { // we would like to just do this // Class superClazz = baseLoader.loadClass(name) // and then access the details using methods of Class // however, this fails because we are in the middle of transforming the subclass and the // classloader // may not have loaded the super. if we force a load now then transforms will not be performed // on // the super class. this may cause us to miss the chance to apply rule injection into the super ClassLoader loader = baseLoader; Class clazz = loadCache.lookupClass(name, loader); if (clazz != null) { return new org.jboss.byteman.agent.check.LoadedClassChecker(clazz); } // ok, instead try loading the bytecode as a resource - user-defined loaders may not support // this but // at least the JVM system and boot loaders should String resourceName = name.replace('.', '/') + ".class"; try { InputStream is; if (baseLoader != null) { is = baseLoader.getResourceAsStream(resourceName); } else { is = ClassLoader.getSystemClassLoader().getResourceAsStream(resourceName); } if (is != null) { int length = is.available(); int count = 0; byte[] bytecode = new byte[length]; while (count < length) { int read = is.read(bytecode, count, length - count); if (read < 0) { throw new IOException("unexpected end of file"); } count += read; } return new org.jboss.byteman.agent.check.BytecodeChecker(bytecode); } else { // throw new IOException("unable to load bytecode for for class " + name); if (isVerbose()) { System.out.println( "Transformer.getClassChecker : unable to load bytecode for for class " + name); } return null; } } catch (IOException e) { // log the exception and return null e.printStackTrace(); return null; } }
private InputStream getInputStreamByPath(String p) { InputStream is = appCL.getResourceAsStream(p); if (is != null) return is; is = Thread.currentThread().getContextClassLoader().getResourceAsStream(p); if (is != null) return is; ClassLoader mycl = this.getClass().getClassLoader(); URL u = mycl.getResource(p); is = mycl.getResourceAsStream(p); if (is != null) return is; ClassLoader pcl = mycl; while ((pcl = pcl.getParent()) != null) { is = pcl.getResourceAsStream(p); if (is != null) return is; } return null; }
static { prop = new Properties(); try { ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); prop.load(classLoader.getResourceAsStream("/DB.properties")); // prop.load(new FileInputStream("Database.properties")); } catch (Exception ex) { ex.printStackTrace(); } }
/** * Loads settings from classpath that represents them using the {@link * SettingsLoaderFactory#loaderFromSource(String)}. */ public Builder loadFromClasspath(String resourceName) throws SettingsException { ClassLoader classLoader = this.classLoader; if (classLoader == null) { classLoader = Classes.getDefaultClassLoader(); } InputStream is = classLoader.getResourceAsStream(resourceName); if (is == null) { return this; } return loadFromStream(resourceName, is); }
private static InputStream loadResourceAsStream(String name) { InputStream in = null; ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader(); if (contextClassLoader != null) { in = contextClassLoader.getResourceAsStream(name); } if (in == null) { in = ISOCurrency.class.getClassLoader().getResourceAsStream(name); } return in; }
// return the resource as a stream private InputStream mapResource(String publicId) { if (publicId == null || id2resource == null) return null; String resourceName = (String) id2resource.get(publicId); ClassLoader loader = null; if (resourceName == null) return null; if (id2loader != null) loader = (ClassLoader) id2loader.get(publicId); if (loader == null) return ClassLoader.getSystemResourceAsStream(resourceName); return loader.getResourceAsStream(resourceName); }
/** * This method is used to load the propertise from the class path. * * @param String * @return Properties. */ private static Properties loadPropertiesFromClassPath(String filename) throws IOException { // use the classloader to find the file in the classpath ClassLoader cl = PropertiesUtil.class.getClassLoader(); InputStream in = cl.getResourceAsStream(filename); if (in == null) { throw new FileNotFoundException("Could not find " + filename + " in classpath"); } Properties properties = new Properties(); properties.load(in); in.close(); return properties; }
public VendorManager() throws IOException { ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); Properties properties = new Properties(); InputStream in = classLoader.getResourceAsStream("myproperties.properties"); properties.load(in); this.xml_rep_path = properties.getProperty("repo.path").toString(); if (xml_rep_path.equalsIgnoreCase("/var/www/empower/empowerdata/")) { // if // (xml_rep_path.equalsIgnoreCase("/home/eleni/Documents/ubi/empower/empower-deliverable-september/empower/")){ String user_home = System.getProperty("user.home"); this.xml_rep_path = user_home + "/empower/empowerdata"; } }
@Test public void testResourceStreamLookupBeforeLoading() throws Exception { InputStream inputStream = classLoader.getResourceAsStream(Foo.class.getName().replace('.', '/') + CLASS_FILE); try { assertThat( inputStream, expectedResourceLookup ? notNullValue(InputStream.class) : nullValue(InputStream.class)); } finally { if (inputStream != null) { inputStream.close(); } } }
private static synchronized String getJavascript() { if (jstext == null) { InputStream istr = null; try { ClassLoader loader = Thread.currentThread().getContextClassLoader(); istr = loader.getResourceAsStream(JAVASCRIPT_RESOURCE); jstext = StringUtil.fromInputStream(istr); istr.close(); } catch (Exception e) { log.error("Can't load javascript", e); } finally { IOUtil.safeClose(istr); } } return jstext; }
protected void transformFeed(File result) throws MojoExecutionException { try { atomFeed = new File(result.getParentFile(), "atom-doctype.xml"); atomFeedClean = new File(result.getParentFile(), "atom.xml"); if (!atomFeed.isFile()) { return; } ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); TransformerFactory factory = TransformerFactory.newInstance(); Transformer transformer = factory.newTransformer(new StreamSource(classLoader.getResourceAsStream(COPY_XSL))); DocumentBuilderFactory dbfactory = DocumentBuilderFactory.newInstance(); dbfactory.setValidating(false); DocumentBuilder builder = dbfactory.newDocumentBuilder(); builder.setEntityResolver( new EntityResolver() { @Override public InputSource resolveEntity(String publicId, String systemId) throws SAXException, IOException { return new InputSource(new StringReader("")); } }); Document xmlDocument = builder.parse(atomFeed); DOMSource source = new DOMSource(xmlDocument); transformer.transform(source, new StreamResult(atomFeedClean)); atomFeed.deleteOnExit(); } catch (TransformerConfigurationException e) { throw new MojoExecutionException("Failed to load JAXP configuration", e); } catch (javax.xml.parsers.ParserConfigurationException e) { throw new MojoExecutionException("Failed to configure parser", e); } catch (org.xml.sax.SAXException e) { throw new MojoExecutionException("Sax exception", e); } catch (java.io.IOException e) { throw new MojoExecutionException("IO Exception", e); } catch (TransformerException e) { throw new MojoExecutionException("Failed to transform to atom feed", e); } }
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, java.io.IOException { String p = req.getParameter("r"); if (p == null || (p = p.trim()).equals("")) { String pi = req.getPathInfo(); return; } byte[] cont = res2cont.get(p); if (cont != null) { resp.setContentType(Mime.getContentType(p)); ServletOutputStream os = resp.getOutputStream(); os.write(cont); os.flush(); return; } InputStream is = null; try { is = appCL.getResourceAsStream(p); // getInputStreamByPath(p) ; if (is == null) { is = new Object().getClass().getResourceAsStream(p); if (is == null) return; } byte[] buf = new byte[1024]; ByteArrayOutputStream baos = new ByteArrayOutputStream(); int len; while ((len = is.read(buf)) >= 0) { baos.write(buf, 0, len); } cont = baos.toByteArray(); res2cont.put(p, cont); resp.setContentType(Mime.getContentType(p)); ServletOutputStream os = resp.getOutputStream(); os.write(cont); os.flush(); return; } finally { if (is != null) is.close(); } }
/** * Only the given locale is searched. Contrary to java.util.ResourceBundle, no strategy for * locating the bundle is implemented in this method. */ String messageFromFile(Locale locale, String filename, String relatedProperty) { String result = null; String bundleBase = propertyToBundles.get(relatedProperty); if (bundleBase == null) { // this property has no translation return null; } String filePath = bundleBase.replace('.', '/'); if (!"en".equals(locale.getLanguage())) { filePath += "_" + locale.getLanguage(); } filePath += "/" + filename; InputStream input = classloader.getResourceAsStream(filePath); if (input != null) { result = readInputStream(filePath, input); } return result; }
// step1 // 计算各个分类的Jd数 public void handler() { ClassLoader classLoader = (new Chi()).getClass().getClassLoader(); InputStream stream = classLoader.getResourceAsStream(SRC_JD); Scanner scanner = new Scanner(stream); String line = null; String jdLine = null; String[] arr = null; Set<String> words = null; Set<String> jdWords = null; Set<String> jds = null; String jd = null; boolean next = false; MajorModel model = null; Splitter splitter = Splitter.on(" ").omitEmptyStrings().trimResults(); while (scanner.hasNextLine()) { line = scanner.nextLine(); if (line == null || line.trim().equals("")) { continue; } if (line.startsWith("jobid:")) { jdLine = line; } else if (line.startsWith("majorcalssify:")) { arr = line.split(":")[1].split(","); jd = jdLine.split(" ")[1]; jdWords = new HashSet<String>(); jd_words.put(jd, jdWords); for (String m : arr) { model = getMajorModel(m); if (model != null) { // 对专业进行验证,确保专业存在 next = true; if (major_words.containsKey(model.getId())) { words = major_words.get(model.getId()); } else { words = new HashSet<String>(); if (model.isMain()) { major_words.put(model.getId(), words); } else { major_words.put(model.getParent().getId(), words); } } if (major_jds.containsKey(model.getId())) { jds = major_jds.get(model.getId()); } else { jds = new HashSet<String>(); if (model.isMain()) { major_jds.put(model.getId(), jds); } else { major_jds.put(model.getParent().getId(), jds); } } jds.add(jd); // get job id } else { next = false; } } } else if (line.startsWith("corp:")) { // ignore // } else if (line.startsWith("title:")) { // ignore } else { if (next) { for (String word : splitter.split(line)) { words.add(word); jdWords.add(word); } jdWords.remove("intro:"); jdWords.remove("title:"); words.remove("intro:"); words.remove("title:"); } } } }
/** {@inheritDoc} */ @Override public GridDeployment getDeployment(GridDeploymentMetadata meta) { assert meta != null; assert ctx.config().isPeerClassLoadingEnabled(); // Validate metadata. assert meta.classLoaderId() != null; assert meta.senderNodeId() != null; assert meta.sequenceNumber() >= -1; assert meta.parentLoader() == null; if (log.isDebugEnabled()) log.debug("Starting to peer-load class based on deployment metadata: " + meta); while (true) { List<SharedDeployment> depsToCheck = null; SharedDeployment dep = null; synchronized (mux) { // Check obsolete request. if (isDeadClassLoader(meta)) return null; List<SharedDeployment> deps = cache.get(meta.userVersion()); if (deps != null) { assert !deps.isEmpty(); for (SharedDeployment d : deps) { if (d.hasParticipant(meta.senderNodeId(), meta.classLoaderId()) || meta.senderNodeId().equals(ctx.localNodeId())) { // Done. dep = d; break; } } if (dep == null) { GridTuple2<Boolean, SharedDeployment> redeployCheck = checkRedeploy(meta); if (!redeployCheck.get1()) { // Checking for redeployment encountered invalid state. if (log.isDebugEnabled()) log.debug("Checking for redeployment encountered invalid state: " + meta); return null; } dep = redeployCheck.get2(); if (dep == null) { // Find existing deployments that need to be checked // whether they should be reused for this request. for (SharedDeployment d : deps) { if (!d.isPendingUndeploy() && !d.isUndeployed()) { if (depsToCheck == null) depsToCheck = new LinkedList<SharedDeployment>(); if (log.isDebugEnabled()) log.debug("Adding deployment to check: " + d); depsToCheck.add(d); } } // If no deployment can be reused, create a new one. if (depsToCheck == null) { dep = createNewDeployment(meta, false); deps.add(dep); } } } } else { GridTuple2<Boolean, SharedDeployment> redeployCheck = checkRedeploy(meta); if (!redeployCheck.get1()) { // Checking for redeployment encountered invalid state. if (log.isDebugEnabled()) log.debug("Checking for redeployment encountered invalid state: " + meta); return null; } dep = redeployCheck.get2(); if (dep == null) // Create peer class loader. dep = createNewDeployment(meta, true); } } if (dep != null) { if (log.isDebugEnabled()) log.debug("Found SHARED or CONTINUOUS deployment after first check: " + dep); // Cache the deployed class. Class<?> cls = dep.deployedClass(meta.className(), meta.alias()); if (cls == null) { U.warn( log, "Failed to load peer class (ignore if class got undeployed during preloading) [alias=" + meta.alias() + ", dep=" + dep + ']'); return null; } return dep; } assert meta.parentLoader() == null; assert depsToCheck != null; assert !depsToCheck.isEmpty(); /* * Logic below must be performed outside of synchronization * because it involves network calls. */ // Check if class can be loaded from existing nodes. // In most cases this loop will find something. for (SharedDeployment d : depsToCheck) { // Load class. Note, that remote node will not load this class. // The class will only be loaded on this node. Class<?> cls = d.deployedClass(meta.className(), meta.alias()); if (cls != null) { synchronized (mux) { if (!d.isUndeployed() && !d.isPendingUndeploy()) { if (!addParticipant(d, meta)) return null; if (log.isDebugEnabled()) log.debug( "Acquired deployment after verifying it's availability on " + "existing nodes [depCls=" + cls + ", dep=" + d + ", meta=" + meta + ']'); return d; } } } else if (log.isDebugEnabled()) { log.debug( "Deployment cannot be reused (class does not exist on participating nodes) [dep=" + d + ", meta=" + meta + ']'); } } // We are here either because all participant nodes failed // or the class indeed should have a separate deployment. for (SharedDeployment d : depsToCheck) { // Temporary class loader. ClassLoader temp = new GridDeploymentClassLoader( GridUuid.randomUuid(), meta.userVersion(), meta.deploymentMode(), true, ctx, ctxLdr, meta.classLoaderId(), meta.senderNodeId(), meta.sequenceNumber(), comm, ctx.config().getNetworkTimeout(), log, ctx.config().getPeerClassLoadingClassPathExclude(), 0, false); String path = U.classNameToResourceName(d.sampleClassName()); // We check if any random class from existing deployment can be // loaded from sender node. If it can, then we reuse existing // deployment. InputStream rsrcIn = temp.getResourceAsStream(path); if (rsrcIn != null) { // We don't need the actual stream. U.closeQuiet(rsrcIn); synchronized (mux) { if (d.isUndeployed() || d.isPendingUndeploy()) continue; // Add new node prior to loading the class, so we attempt // to load the class from the latest node. if (!addParticipant(d, meta)) { if (log.isDebugEnabled()) log.debug( "Failed to add participant to deployment " + "[meta=" + meta + ", dep=" + dep + ']'); return null; } } Class<?> depCls = d.deployedClass(meta.className(), meta.alias()); if (depCls == null) { U.error( log, "Failed to peer load class after loading it as a resource [alias=" + meta.alias() + ", dep=" + dep + ']'); return null; } if (log.isDebugEnabled()) log.debug( "Acquired deployment class after verifying other class " + "availability on sender node [depCls=" + depCls + ", rndCls=" + d.sampleClass() + ", sampleClsName=" + d.sampleClassName() + ", meta=" + meta + ']'); return d; } else if (log.isDebugEnabled()) log.debug( "Deployment cannot be reused (random class could not be loaded from sender node) [dep=" + d + ", meta=" + meta + ']'); } synchronized (mux) { if (log.isDebugEnabled()) log.debug( "None of the existing class-loaders fit (will try to create a new one): " + meta); // Check obsolete request. if (isDeadClassLoader(meta)) return null; // Check that deployment picture has not changed. List<SharedDeployment> deps = cache.get(meta.userVersion()); if (deps != null) { assert !deps.isEmpty(); boolean retry = false; for (SharedDeployment d : deps) { // Double check if sender was already added. if (d.hasParticipant(meta.senderNodeId(), meta.classLoaderId())) { dep = d; retry = false; break; } // New deployment was added while outside of synchronization. // Need to recheck it again. if (!d.isPendingUndeploy() && !d.isUndeployed() && !depsToCheck.contains(d)) retry = true; } if (retry) { if (log.isDebugEnabled()) log.debug("Retrying due to concurrency issues: " + meta); // Outer while loop. continue; } if (dep == null) { // No new deployments were added, so we can safely add ours. dep = createNewDeployment(meta, false); deps.add(dep); if (log.isDebugEnabled()) log.debug( "Adding new deployment within second check [dep=" + dep + ", meta=" + meta + ']'); } } else { dep = createNewDeployment(meta, true); if (log.isDebugEnabled()) log.debug( "Created new deployment within second check [dep=" + dep + ", meta=" + meta + ']'); } } if (dep != null) { // Cache the deployed class. Class<?> cls = dep.deployedClass(meta.className(), meta.alias()); if (cls == null) { U.warn( log, "Failed to load peer class (ignore if class got undeployed during preloading) [alias=" + meta.alias() + ", dep=" + dep + ']'); return null; } } return dep; } }
/** * @param filenames * @exception Exception if internal error */ public void loadMultiPanelFromSpecifiedFiles(String filenames[]) throws Exception { int nFiles = filenames.length; SingleImagePanel imagePanels[] = new SingleImagePanel[nFiles]; String orientations[][] = new String[nFiles][]; String views[] = new String[nFiles]; String lateralityViewAndModifiers[] = new String[nFiles]; String lateralities[] = new String[nFiles]; int widths[] = new int[nFiles]; int heights[] = new int[nFiles]; PixelSpacing spacing[] = new PixelSpacing[nFiles]; String rowOrientations[] = new String[nFiles]; String columnOrientations[] = new String[nFiles]; HashMap eventContexts = new HashMap(); double maximumHorizontalExtentInMm = 0; double maximumVerticalExtentInMm = 0; StructuredReport sr[] = new StructuredReport[nFiles]; int nImages = 0; int nCAD = 0; ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); for (int f = 0; f < nFiles; ++f) { try { String filename = filenames[f]; DicomInputStream distream = null; InputStream in = classLoader.getResourceAsStream(filename); if (in != null) { distream = new DicomInputStream(in); } else { distream = new DicomInputStream(new File(filename)); } AttributeList list = new AttributeList(); list.read(distream); if (list.isImage()) { int i = nImages++; System.err.println("IMAGE [" + i + "] is file " + f + " (" + filenames[f] + ")"); orientations[i] = getPatientOrientation(list); // System.err.println("IMAGE ["+i+"] orientation="+(orientations[i] == null && // orientations[i].length == 2 ? "" : (orientations[i][0] + " " + orientations[i][1]))); views[i] = getView(list); // System.err.println("IMAGE ["+i+"] view="+views[i]); lateralityViewAndModifiers[i] = getImageLateralityViewModifierAndViewModifier(list); // System.err.println("IMAGE ["+i+"] // lateralityViewAndModifiers="+lateralityViewAndModifiers[i]); // System.err.println("File "+filenames[f]+": "+lateralityViewAndModifiers[i]); lateralities[i] = getLaterality(list); // System.err.println("IMAGE ["+i+"] laterality="+lateralities[i]); spacing[i] = new PixelSpacing(list); // System.err.println("IMAGE ["+i+"] spacing="+spacing[i]); SourceImage sImg = new SourceImage(list); BufferedImage img = sImg.getBufferedImage(); widths[i] = sImg.getWidth(); heights[i] = sImg.getHeight(); boolean shareVOIEventsInStudy = false; // does not seem to work anyway, since adding VOITransform to panel constructor // :( EventContext eventContext = new EventContext(Integer.toString(i)); SingleImagePanel imagePanel = makeNewImagePanel(sImg, eventContext); imagePanel.setDemographicAndTechniqueAnnotations( new DemographicAndTechniqueAnnotations(list), "SansSerif", Font.PLAIN, 10, Color.pink); imagePanel.setOrientationAnnotations( new OrientationAnnotations(rowOrientations[i], columnOrientations[i]), "SansSerif", Font.PLAIN, 20, Color.pink); imagePanel.setPixelSpacingInSourceImage( spacing[i].getSpacing(), spacing[i].getDescription()); if (Attribute.getSingleStringValueOrEmptyString(list, TagFromName.VOILUTFunction) .equals("SIGMOID")) { imagePanel.setVOIFunctionToLogistic(); } imagePanels[i] = imagePanel; } else { throw new DicomException("Unsupported SOP Class in file " + filenames[f]); } } catch (Exception e) { // FileNotFoundException,IOException,DicomException e.printStackTrace(System.err); } } // int imagesPerRow = nImages; // i.e., 1 -> 1, 2 -> 1, 4 -> 4, 5 -> 4, 8 -> 4 // int imagesPerCol = 1; int imagesPerRow = nImages >= 8 ? 8 : nImages; // i.e., 1 -> 1, 2 -> 1, 4 -> 4, 5 -> 4, 8 -> 4 int imagesPerCol = (nImages - 1) / imagesPerRow + 1; // i.e., 1 -> 1, 2 -> 2, 4 -> 1, 5 -> 2, 8 -> 2 int singleWidth = frameWidth / imagesPerRow; int singleHeight = frameHeight / imagesPerCol; if (nImages == 1 && singleWidth > singleHeight) { singleWidth = singleWidth / 2; // use only half the screen for a single view and a landscape monitor } for (int i = 0; i < nImages; ++i) { DisplayedAreaSelection displayedAreaSelection = null; displayedAreaSelection = new DisplayedAreaSelection( widths[i], heights[i], 0, 0, widths[i], heights[i], true, // in case spacing was not supplied 0, 0, 0, 0, 0, false /*crop*/); imagePanels[i].setDisplayedAreaSelection(displayedAreaSelection); imagePanels[i].setPreTransformImageRelativeCoordinates(null); } SingleImagePanel.deconstructAllSingleImagePanelsInContainer(multiPanel); multiPanel.removeAll(); multiPanel.setLayout(new GridLayout(imagesPerCol, imagesPerRow)); multiPanel.setBackground(Color.black); for (int x = 0; x < imagesPerCol; ++x) { for (int y = 0; y < imagesPerRow; ++y) { int i = x * imagesPerRow + y; if (i < nImages) { imagePanels[i].setPreferredSize(new Dimension(singleWidth, singleHeight)); multiPanel.add(imagePanels[i]); } } } frame.getContentPane().validate(); frame.getContentPane().repaint(); }