Example usage for java.lang ClassLoader getSystemResource

List of usage examples for java.lang ClassLoader getSystemResource

Introduction

In this page you can find the example usage for java.lang ClassLoader getSystemResource.

Prototype

public static URL getSystemResource(String name) 

Source Link

Document

Find a resource of the specified name from the search path used to load classes.

Usage

From source file:org.apache.james.mailbox.elasticsearch.json.MessageToElasticSearchJsonTest.java

@Test
public void convertToJsonWithoutAttachmentShouldConvertEmailBoby() throws IOException {
    // Given//from ww  w  .j a  va 2 s  .  c  o  m
    MailboxMessage message = new SimpleMailboxMessage(MESSAGE_ID, null, SIZE, BODY_START_OCTET,
            new SharedByteArrayInputStream(IOUtils.toByteArray(
                    ClassLoader.getSystemResourceAsStream("eml/emailWithNonIndexableAttachment.eml"))),
            new FlagsBuilder().add(Flags.Flag.DELETED, Flags.Flag.SEEN).add("debian", "security").build(),
            propertyBuilder, MAILBOX_ID);
    message.setModSeq(MOD_SEQ);
    message.setUid(UID);

    // When
    MessageToElasticSearchJson messageToElasticSearchJson = new MessageToElasticSearchJson(
            new DefaultTextExtractor(), ZoneId.of("Europe/Paris"), IndexAttachments.NO);
    String convertToJsonWithoutAttachment = messageToElasticSearchJson.convertToJsonWithoutAttachment(message,
            ImmutableList.of(new MockMailboxSession("username").getUser()));

    // Then
    assertThatJson(convertToJsonWithoutAttachment).when(IGNORING_ARRAY_ORDER).when(IGNORING_VALUES)
            .isEqualTo(IOUtils.toString(ClassLoader
                    .getSystemResource("eml/emailWithNonIndexableAttachmentWithoutAttachment.json")));
}

From source file:org.zaproxy.zap.control.ExtensionFactory.java

/**
 * Finds and returns the URL to a resource with the given class loader, or
 * system class loader if {@code null}, for the given or default locales.
 * <p>/*from   w  w w .ja va 2  s .  c  om*/
 * The resource pathname will be constructed using the parameters package
 * name, file name, file extension and candidate locales. The candidate
 * locales are created from the given locale using the method
 * {@code HelpUtilities#getCandidates(Locale)}.
 * </p>
 * <p>
 * The resource pathname is constructed as:
 *
 * <pre>
 * &quot;package name&quot; + &quot;candidate locale&quot; + '/' + &quot;file name&quot; + &quot;candidate locale&quot; + &quot;file extension&quot;
 * </pre>
 *
 * For example, with the following parameters:
 * <ul>
 * <li>package name - /org/zaproxy/zap/extension/example/resources/help</li>
 * <li>file name - helpset</li>
 * <li>file extension - .hs</li>
 * <li>locale - es_ES</li>
 * </ul>
 * and default locale "en_GB", it would produce the following resource
 * pathnames:
 *
 * <pre>
 * /org/zaproxy/zap/extension/example/resources/help_es_ES/helpset_es_ES.hs
 * /org/zaproxy/zap/extension/example/resources/help_es/helpset_es.hs
 * /org/zaproxy/zap/extension/example/resources/help/helpset.hs
 * /org/zaproxy/zap/extension/example/resources/help_en_GB/helpset_en_GB.hs
 * /org/zaproxy/zap/extension/example/resources/help_en/helpset_en.hs
 * </pre>
 *
 * The URL of the first existent resource is returned.
 * </p>
 *
 * @param cl the class loader that will be used to get the resource,
 * {@code null} the system class loader is used.
 * @param packageName the name of the package where the resource is
 * @param fileName the file name of the resource
 * @param fileExtension the file extension of the resource
 * @param locale the target locale of the required resource
 * @return An {@code URL} with the path to the resource or {@code null} if
 * not found.
 * @see HelpUtilities#getCandidates(Locale)
 */
// Implementation based (read copied) from:
// javax.help.HelpUtilities#getLocalizedResource(ClassLoader cl, String front, String back, Locale locale, boolean tryRead)
// Changes:
// - Removed the "tryRead" flag since it's not needed (it's set to try to read always);
// - Replaced the use of StringBuffer with StringBuilder;
// - Renamed parameters "front" to "packageName" and "back" to "name";
// - Renamed variable "tail" to "candidateLocale";
// - Renamed variable "name" to "resource";
// - Added type parameter to "tails" enumeration (now "candidateLocales"), @SuppressWarnings annotation and removed the
// String cast;
// - Changed to use try-with-resource statement to manage the input stream.
// - Changed to also append the "candidateLocale" to the packageName followed by character '/';
private static URL findResource(ClassLoader cl, String packageName, String fileName, String fileExtension,
        Locale locale) {
    URL url;

    for (@SuppressWarnings("unchecked")
    Enumeration<String> candidateLocales = HelpUtilities.getCandidates(locale); candidateLocales
            .hasMoreElements();) {
        String candidateLocale = candidateLocales.nextElement();
        String resource = (new StringBuilder(packageName)).append(candidateLocale).append('/').append(fileName)
                .append(candidateLocale).append(fileExtension).toString();
        if (cl == null) {
            url = ClassLoader.getSystemResource(resource);
        } else {
            url = cl.getResource(resource);
        }
        if (url != null) {
            // Try doing an actual read to be sure it exists
            try (InputStream is = url.openConnection().getInputStream()) {
                if (is != null && is.read() != -1) {
                    return url;
                }
            } catch (Throwable t) {
                // ignore and continue looking
            }
        }
    }
    return null;
}

From source file:client.InterfaceJeu.java

public void distribuerCartes(String cartesList) {
    //System.out.println("distribution des cartes");
    nettoyerMain();//from   w w w . j ava  2  s.  co  m
    if (!cartesList.equals("[]")) {
        try {
            this.cartes = (JSONArray) parser.parse(cartesList);
        } catch (Exception e) {
            System.out.println("error json : " + e.getLocalizedMessage());
        }
        Iterator it = cartes.iterator();
        int i = 0;
        int j = 0;
        while (it.hasNext()) {
            obj = (JSONObject) it.next();
            auxName = obj.get("hauteur").toString() + '-' + obj.get("couleur").toString();
            // System.out.println(auxName);
            /*ImageIcon img=new ImageIcon(ClassLoader.getSystemResource("images/"+auxName));
            System.out.println(img);
            JLabel label = new JLabel();
            label.setPreferredSize(new Dimension(img.getIconWidth(), img.getIconHeight()));
            //label.setIcon(img);
            label.setText("youpi!!");
            jPanel2.add(label);
            jPanel2.revalidate(); 
            jPanel2.repaint(); */
            imgCartes.add(
                    new JLabel(new ImageIcon(ClassLoader.getSystemResource("images/" + auxName + ".gif"))));
            imgCartes.get(i).setLayout(new BorderLayout());
            imgCartes.get(i).setSize(62, 89);
            imgCartes.get(i).setName(auxName);
            imgCartes.get(i).addMouseListener(new MouseListener() {

                @Override
                public void mouseClicked(MouseEvent e) {
                    //verifier si c'est son tour d'abord
                    if ((tourName.equals(c.pseudo) && !interSession)
                            || (interSession && (role.equals("president") || role.equals("vicepresident")))) {
                        if (cartesSelectionnees.contains(e.getComponent())) {
                            deselectionnerCarte(e.getComponent());
                        } else {
                            selectionnerCarte(e.getComponent());
                        }
                    }
                    //System.out.println(e.getComponent().getClass());
                }

                @Override
                public void mousePressed(MouseEvent e) {
                }

                @Override
                public void mouseReleased(MouseEvent e) {
                }

                @Override
                public void mouseEntered(MouseEvent e) {
                }

                @Override
                public void mouseExited(MouseEvent e) {
                }
            });
            imgCartes.get(i).setLocation(j, jPanel1.getHeight() - 92);
            this.jPanel1.add(imgCartes.get(i), BorderLayout.CENTER);
            i++;
            j = j + 28;

            jPanel1.repaint();
            //                ImageIcon tempImg=new ImageIcon("../images/"+auxName+".gif");
            //                imgCartes.add(tempImg);
            //                Image b=tempImg.getImage();
            //                this.getGraphics().drawImage(b, 192, 280, null);
            //                tempImg.paintIcon(this, null, 192, 280);
            //                this.jPanel2.add(tempImg);
        }

        jButton1.setVisible(true);
        jButton1.addMouseListener(new MouseListener() {

            @Override
            public void mouseClicked(MouseEvent e) {
                if (jButton1.isEnabled()) {
                    if (interSession) {
                        donnerCartes();
                    } else {
                        jouerCartes();
                    }
                }
            }

            @Override
            public void mousePressed(MouseEvent e) {
            }

            @Override
            public void mouseReleased(MouseEvent e) {
            }

            @Override
            public void mouseEntered(MouseEvent e) {
            }

            @Override
            public void mouseExited(MouseEvent e) {
            }
        });

        jButton2.setVisible(true);
        jButton2.addMouseListener(new MouseListener() {

            @Override
            public void mouseClicked(MouseEvent e) {
                if (jButton2.isEnabled()) {
                    passer();
                }
            }

            @Override
            public void mousePressed(MouseEvent e) {
            }

            @Override
            public void mouseReleased(MouseEvent e) {
            }

            @Override
            public void mouseEntered(MouseEvent e) {
            }

            @Override
            public void mouseExited(MouseEvent e) {
            }
        });
    }
}

From source file:org.obm.push.json.JSONServiceCompatibilityTest.java

private File[] findJsonFiles() throws URISyntaxException {
    URL folderSource = ClassLoader.getSystemResource("compatibility");
    File[] jsonFiles = new File(folderSource.toURI()).listFiles(new FilenameFilter() {
        @Override/*from ww w  .  j  a  v a2 s. c o m*/
        public boolean accept(File dir, String name) {
            return name.endsWith(".json");
        }
    });
    return jsonFiles;
}

From source file:edu.stanford.epadd.launcher.Splash.java

private static void parseOptions(String[] args) throws ParseException {
    // set javawebstart.version to a dummy value if not already set (might happen when running with java -jar from cmd line)
    // exit.jsp doesn't allow us to showdown unless this prop is set
    if (System.getProperty("javawebstart.version") == null)
        System.setProperty("javawebstart.version", "UNKNOWN");

    if (args.length > 0) {
        out.print(args.length + " argument(s): ");
        for (int i = 0; i < args.length; i++)
            out.print(args[i] + " ");
        out.println();/*from w  ww.  j av a 2 s  .c o m*/
    }

    Options options = getOpt();
    CommandLineParser parser = new PosixParser();
    CommandLine cmd = parser.parse(options, args);

    if (cmd.hasOption("help")) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("ePADD batch mode", options);
        return;
    }

    debug = false;
    if (cmd.hasOption("debug")) {
        URL url = ClassLoader.getSystemResource("log4j.properties.debug");
        out.println("Loading logging configuration from url: " + url);
        PropertyConfigurator.configure(url);
        debug = true;
    } else if (cmd.hasOption("debug-address-book")) {
        URL url = ClassLoader.getSystemResource("log4j.properties.debug.ab");
        out.println("Loading logging configuration from url: " + url);
        PropertyConfigurator.configure(url);
        debug = false;
    } else if (cmd.hasOption("debug-groups")) {
        URL url = ClassLoader.getSystemResource("log4j.properties.debug.groups");
        out.println("Loading logging configuration from url: " + url);
        PropertyConfigurator.configure(url);
        debug = false;
    }

    if (cmd.hasOption("no-browser-open") || System.getProperty("nobrowseropen") != null)
        browserOpen = false;

    if (cmd.hasOption("port")) {
        String portStr = cmd.getOptionValue('p');
        try {
            PORT = Integer.parseInt(portStr);
            String mesg = " Running on port: " + PORT;
            out.println(mesg);
        } catch (NumberFormatException nfe) {
            out.println("invalid port number " + portStr);
        }
    }

    if (cmd.hasOption("start-page"))
        startPage = cmd.getOptionValue("start-page");

    /*
      if (!cmd.hasOption("no-shutdown")) {
      // arrange to kill Muse after a period of time, we don't want the server to run forever
              
      // i clearly have too much time on my hands right now...
      long secs = KILL_AFTER_MILLIS/1000;
      long hh = secs/3600;
      long mm = (secs%3600)/60;
      long ss = secs % (60);
      out.print ("ePADD will shut down automatically after ");
      if (hh != 0)
      out.print (hh  + " hours ");
      if (mm != 0 || (hh != 0 && ss != 0))
      out.print (mm + " minutes");
      if (ss != 0)
      out.print (ss + " seconds");
      out.println();
              
      Timer timer = new Timer(); 
      TimerTask tt = new ShutdownTimerTask();
      timer.schedule (tt, KILL_AFTER_MILLIS);
      }
    */
    System.setSecurityManager(null); // this is important   
}

From source file:ee.ria.xroad.proxy.serverproxy.MetadataServiceHandlerTest.java

private String readFile(String filename) throws IOException, URISyntaxException {
    return new String(Files.readAllBytes(Paths.get(ClassLoader.getSystemResource(filename).toURI())), "UTF-8");
}

From source file:org.owasp.esapi.reference.DefaultSecurityConfiguration.java

/**
 * {@inheritDoc}//from w w w  . j  a v  a  2  s. c om
 */
public File getResourceFile(String filename) {
    logSpecial("Attempting to load " + filename + " as resource file via file I/O.");

    if (filename == null) {
        logSpecial("Failed to load properties via FileIO. Filename is null.");
        return null; // not found.
    }

    File f = null;

    // first, allow command line overrides. -Dorg.owasp.esapi.resources
    // directory
    f = new File(customDirectory, filename);
    if (customDirectory != null && f.canRead()) {
        logSpecial("Found in 'org.owasp.esapi.resources' directory: " + f.getAbsolutePath());
        return f;
    } else {
        logSpecial("Not found in 'org.owasp.esapi.resources' directory or file not readable: "
                + f.getAbsolutePath());
    }

    // if not found, then try the programmatically set resource directory
    // (this defaults to SystemResource directory/resourceFile
    URL fileUrl = ClassLoader.getSystemResource(resourceDirectory + "/" + filename);
    if (fileUrl == null) {
        fileUrl = ClassLoader.getSystemResource("esapi/" + filename);
    }

    if (fileUrl != null) {
        String fileLocation = fileUrl.getFile();
        f = new File(fileLocation);
        if (f.exists()) {
            logSpecial("Found in SystemResource Directory/resourceDirectory: " + f.getAbsolutePath());
            return f;
        } else {
            logSpecial("Not found in SystemResource Directory/resourceDirectory (this should never happen): "
                    + f.getAbsolutePath());
        }
    } else {
        logSpecial("Not found in SystemResource Directory/resourceDirectory: " + resourceDirectory
                + File.separator + filename);
    }

    // If not found, then try immediately under user's home directory first in
    //      userHome + "/.esapi"      and secondly under
    //      userHome + "/esapi"
    // We look in that order because of backward compatibility issues.
    String homeDir = userHome;
    if (homeDir == null) {
        homeDir = ""; // Without this,   homeDir + "/.esapi"   would produce
        // the string      "null/.esapi"      which surely is not intended.
    }
    // First look under ".esapi" (for reasons of backward compatibility).
    f = new File(homeDir + "/.esapi", filename);
    if (f.canRead()) {
        logSpecial("[Compatibility] Found in 'user.home' directory: " + f.getAbsolutePath());
        return f;
    } else {
        // Didn't find it under old directory ".esapi" so now look under the "esapi" directory.
        f = new File(homeDir + "/esapi", filename);
        if (f.canRead()) {
            logSpecial("Found in 'user.home' directory: " + f.getAbsolutePath());
            return f;
        } else {
            logSpecial("Not found in 'user.home' (" + homeDir + ") directory: " + f.getAbsolutePath());
        }
    }

    // return null if not found
    return null;
}

From source file:gov.jgi.meta.MetaUtils.java

public static void configureLog4j() {
    // configure the log4j system for hadoop map jobs

    String log4jConfigurationFile = System.getProperty("log4j.properties");

    System.out.println("configuring log4j using: " + log4jConfigurationFile);

    URL u = ClassLoader.getSystemResource(log4jConfigurationFile);
    if (u == null) {
        System.err.println("unable to find " + log4jConfigurationFile + " ... skipping");
    } else {/*w  ww  . ja v  a 2  s .  co  m*/
        PropertyConfigurator.configure(log4jConfigurationFile);
    }
}

From source file:client.InterfaceJeu.java

public void poserCartes(String cartesList) {
    try {/*from  w  w w.  j  ava2 s  .  c om*/
        imgCartesPosees.clear();
        jPanel2.removeAll();
        if (!cartesList.equals("[]")) {
            this.cartesPosees = (JSONArray) parser.parse(cartesList);
            Iterator it = cartesPosees.iterator();
            int i = 0;
            int j = 0;
            while (it.hasNext()) {
                obj = (JSONObject) it.next();
                auxName = obj.get("hauteur").toString() + '-' + obj.get("couleur").toString();
                imgCartesPosees.add(
                        new JLabel(new ImageIcon(ClassLoader.getSystemResource("images/" + auxName + ".gif"))));
                imgCartesPosees.get(i).setLayout(new BorderLayout());
                imgCartesPosees.get(i).setSize(62, 89);
                imgCartesPosees.get(i).setName(auxName);
                imgCartesPosees.get(i).setLocation(j, jPanel2.getHeight() - 92);
                this.jPanel2.add(imgCartesPosees.get(i), BorderLayout.CENTER);
                i++;
                j = j + 60;

                jPanel2.setAlignmentY(CENTER_ALIGNMENT);
                jPanel2.repaint();
            }
        }
    } catch (Exception e) {
        System.out.println("error cartePosees : " + e.getLocalizedMessage());
    }

    System.out.println(imgCartesPosees);
}

From source file:org.apache.pig.test.TestGrunt.java

public void testRegisterWithQuotes() throws Throwable {
    PigServer server = new PigServer(ExecType.MAPREDUCE, cluster.getProperties());
    PigContext context = server.getPigContext();

    String strCmd = "register 'pig-withouthadoop.jar'\n";

    ByteArrayInputStream cmd = new ByteArrayInputStream(strCmd.getBytes());
    InputStreamReader reader = new InputStreamReader(cmd);

    Grunt grunt = new Grunt(new BufferedReader(reader), context);

    grunt.exec();/*from   w ww . ja v  a2s  . c  o m*/
    assertTrue(context.extraJars.contains(ClassLoader.getSystemResource("pig-withouthadoop.jar")));
}