Example usage for java.lang ClassLoader getResource

List of usage examples for java.lang ClassLoader getResource

Introduction

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

Prototype

public URL getResource(String name) 

Source Link

Document

Finds the resource with the given name.

Usage

From source file:org.apache.hadoop.fs.http.server.TestHttpFSWithKerberos.java

private void createHttpFSServer() throws Exception {
    File homeDir = TestDirHelper.getTestDir();
    Assert.assertTrue(new File(homeDir, "conf").mkdir());
    Assert.assertTrue(new File(homeDir, "log").mkdir());
    Assert.assertTrue(new File(homeDir, "temp").mkdir());
    HttpFSServerWebApp.setHomeDirForCurrentThread(homeDir.getAbsolutePath());

    File secretFile = new File(new File(homeDir, "conf"), "secret");
    Writer w = new FileWriter(secretFile);
    w.write("secret");
    w.close();/*from   w  w  w  .  j ava 2  s. c o m*/

    //HDFS configuration
    File hadoopConfDir = new File(new File(homeDir, "conf"), "hadoop-conf");
    hadoopConfDir.mkdirs();
    String fsDefaultName = TestHdfsHelper.getHdfsConf().get(CommonConfigurationKeysPublic.FS_DEFAULT_NAME_KEY);
    Configuration conf = new Configuration(false);
    conf.set(CommonConfigurationKeysPublic.FS_DEFAULT_NAME_KEY, fsDefaultName);
    File hdfsSite = new File(hadoopConfDir, "hdfs-site.xml");
    OutputStream os = new FileOutputStream(hdfsSite);
    conf.writeXml(os);
    os.close();

    conf = new Configuration(false);
    conf.set("httpfs.proxyuser.client.hosts", "*");
    conf.set("httpfs.proxyuser.client.groups", "*");

    conf.set("httpfs.authentication.type", "kerberos");

    conf.set("httpfs.authentication.signature.secret.file", secretFile.getAbsolutePath());
    File httpfsSite = new File(new File(homeDir, "conf"), "httpfs-site.xml");
    os = new FileOutputStream(httpfsSite);
    conf.writeXml(os);
    os.close();

    ClassLoader cl = Thread.currentThread().getContextClassLoader();
    URL url = cl.getResource("webapp");
    WebAppContext context = new WebAppContext(url.getPath(), "/webhdfs");
    Server server = TestJettyHelper.getJettyServer();
    server.addHandler(context);
    server.start();
    HttpFSServerWebApp.get().setAuthority(TestJettyHelper.getAuthority());
}

From source file:edu.harvard.hul.ois.drs.pdfaconvert.clients.HttpClientIntegrationTest.java

@Test
public void noFileParameterValueTest() throws URISyntaxException {
    ClassLoader loader = Thread.currentThread().getContextClassLoader();
    URL fileUrl = loader.getResource(INPUT_FILENAME);
    File inputFile = new File(fileUrl.toURI());
    assertNotNull(inputFile);/*from ww  w.ja v a2 s . c  o m*/
    assertTrue(inputFile.exists());
    assertTrue(inputFile.isFile());
    assertTrue(inputFile.canRead());

    CloseableHttpClient httpclient = HttpClients.createDefault();
    String url = LOCAL_TOMCAT_SERVICE_URL + "?file=";
    HttpGet httpGet = new HttpGet(url);

    CloseableHttpResponse response = null;
    try {
        logger.debug("executing request " + httpGet.getRequestLine());
        response = httpclient.execute(httpGet);
        StatusLine statusLine = response.getStatusLine();
        logger.debug("Response status line : " + statusLine);
        assertEquals(400, statusLine.getStatusCode());
    } catch (IOException e) {
        logger.error("Something went wrong...", e);
        fail(e.getMessage());
    } finally {
        if (response != null) {
            try {
                response.close();
                httpclient.close();
            } catch (IOException e) {
                // nothing to do
                ;
            }
        }
    }
    logger.debug("DONE");
}

From source file:edu.harvard.hul.ois.drs.pdfaconvert.clients.HttpClientIntegrationTest.java

@Test
public void noFileParameterTest() throws URISyntaxException {
    ClassLoader loader = Thread.currentThread().getContextClassLoader();
    URL fileUrl = loader.getResource(INPUT_FILENAME);
    File inputFile = new File(fileUrl.toURI());
    assertNotNull(inputFile);/*from   w w  w  . j a v a2  s  .  co m*/
    assertTrue(inputFile.exists());
    assertTrue(inputFile.isFile());
    assertTrue(inputFile.canRead());

    CloseableHttpClient httpclient = HttpClients.createDefault();
    String url = LOCAL_TOMCAT_SERVICE_URL;
    HttpGet httpGet = new HttpGet(url);

    CloseableHttpResponse response = null;
    try {
        logger.debug("executing request " + httpGet.getRequestLine());
        response = httpclient.execute(httpGet);
        StatusLine statusLine = response.getStatusLine();
        logger.debug("Response status line : " + statusLine);
        assertEquals(400, statusLine.getStatusCode());
    } catch (IOException e) {
        logger.error("Something went wrong...", e);
        fail(e.getMessage());
    } finally {
        if (response != null) {
            try {
                response.close();
                httpclient.close();
            } catch (IOException e) {
                // nothing to do
                ;
            }
        }
    }
    logger.debug("DONE");
}

From source file:com.h3xstream.findbugs.test.service.FindBugsLauncher.java

/**
 * The minimum requirement to have a "valid" archive plugin is to include
 * findbugs.xml, messages.xml and MANIFEST.MF files. The rest of the
 * resources are load using the parent ClassLoader (Not requires to be in
 * the jar)./*w w  w  .  j  av a  2  s.  c  om*/
 * <p>
 * Instead of building a file on disk, the result of the stream is kept in
 * memory and return as a byte array.
 *
 * @return
 * @throws IOException
 * @throws URISyntaxException 
 */
private byte[] buildFakePluginJar() throws IOException, URISyntaxException {
    ClassLoader cl = getClass().getClassLoader();

    ByteArrayOutputStream buffer = new ByteArrayOutputStream();
    JarOutputStream jar = new JarOutputStream(buffer);

    final URL metadata = cl.getResource("metadata");
    if (metadata != null) {
        final File dir = new File(metadata.toURI());

        //Add files to the jar stream
        addFilesToStream(cl, jar, dir, "");
    }
    jar.finish();
    jar.close();

    return buffer.toByteArray();
}

From source file:ilearn.orb.controller.AnnotationController.java

@RequestMapping(value = "/annotation/{userid}", method = RequestMethod.GET)
public ModelAndView textUserAnnotation(Locale locale, ModelMap modelMap, HttpServletRequest request,
        HttpSession session, @PathVariable("userid") Integer userid) {
    try {//w  w w  .  j a  va2s. c  o m
        request.setCharacterEncoding("UTF-8");
    } catch (UnsupportedEncodingException e1) {
        e1.printStackTrace();
    }
    txModule = new TextAnnotationModule();
    ModelAndView model = new ModelAndView();
    model.setViewName("annotation");
    try {
        User[] students = null;
        UserProfile p = null;
        User selectedStudent = null;
        if (userid < 0) {
            students = HardcodedUsers.defaultStudents();
            selectedStudent = selectedStudent(students, userid.intValue());
            // p = HardcodedUsers.defaultProfile(selectedStudent.getId());
            String json = UserServices
                    .getDefaultProfile(HardcodedUsers.defaultProfileLanguage(selectedStudent.getId()));
            if (json != null)
                p = new Gson().fromJson(json, UserProfile.class);
        } else {
            Gson gson = new GsonBuilder().registerTypeAdapter(java.util.Date.class, new UtilDateDeserializer())
                    .setDateFormat(DateFormat.LONG).create();
            String json = UserServices.getProfiles(Integer.parseInt(session.getAttribute("id").toString()),
                    session.getAttribute("auth").toString());
            students = gson.fromJson(json, User[].class);
            selectedStudent = selectedStudent(students, userid.intValue());
            json = UserServices.getJsonProfile(userid, session.getAttribute("auth").toString());
            if (json != null)
                p = new Gson().fromJson(json, UserProfile.class);
        }
        modelMap.put("profileId", userid);
        modelMap.put("selectedStudent", selectedStudent);
        modelMap.put("students", students);
        modelMap.put("selectedProfile", p);

        ClassLoader classLoader = getClass().getClassLoader();
        File file = new File(classLoader
                .getResource("data/" + (selectedStudent.getLanguage().toLowerCase()) + ".json").getFile());
        String js = LocalStorageTextFileHandler.loadFileAsString(file);
        Groups grps = new Gson().fromJson(js, Groups.class);
        modelMap.put("presents", grps);

    } catch (NumberFormatException e) {
        //e.printStackTrace();
    } catch (Exception e) {
        e.printStackTrace();
    }
    return model;
}

From source file:com.adaptris.core.management.webserver.JettyServerComponent.java

private InputStream connectToFile(String localFile) throws IOException {
    InputStream in = null;//  w  w w  .j a v a2s.  c  o m
    File f = new File(localFile);
    if (f.exists()) {
        in = new FileInputStream(f);
    } else {
        ClassLoader c = this.getClass().getClassLoader();
        URL u = c.getResource(localFile);
        if (u != null) {
            in = u.openStream();
        }
    }
    return in;
}

From source file:com.impetus.kundera.cache.ehcache.EhCacheProvider.java

/**
* Load resource.//from  w  w  w  . jav  a2s  . c  om
* 
* @param configurationResourceName
*            the configuration resource name
* @return the uRL
*/
private URL loadResource(String configurationResourceName) {
    ClassLoader standardClassloader = ClassLoaderUtil.getStandardClassLoader();
    URL url = null;
    if (standardClassloader != null) {
        url = standardClassloader.getResource(configurationResourceName);
    }
    if (url == null) {
        url = this.getClass().getResource(configurationResourceName);
    }
    log.info("Creating EhCacheFactory from a specified resource: " + configurationResourceName
            + " Resolved to URL: " + url);

    if (url == null) {
        log.warn("A configurationResourceName was set to " + configurationResourceName
                + " but the resource could not be loaded from the classpath."
                + "Ehcache will configure itself using defaults.");
    }
    return url;
}

From source file:com.aurel.track.dbase.HandleHome.java

public static PropertiesConfiguration getMergedCrmConfiguration(PropertiesConfiguration dbcfg) {
    String propFile = "CrmTorque.properties";
    ClassLoader cl = HandleHome.class.getClassLoader();
    InputStream in = null;//from  w w w. jav  a  2 s. co m
    try {
        URL torqueURL = cl.getResource(propFile);
        in = torqueURL.openStream();
        if (dbcfg == null) {
            dbcfg = new PropertiesConfiguration();
        }
        dbcfg.load(in);
        in.close();
        if (firstTimeMerge) {
            LOGGER.info("Obtained another database configuration from " + propFile + ".");
            firstTimeMerge = false;
        }
    } catch (Exception e) {
        String emsg = e.getMessage();
        if (emsg == null) {
            emsg = "";
        }
    }
    return dbcfg;
}

From source file:io.fabric8.mq.controller.coordination.KubernetesControl.java

private String getOrCreateBrokerReplicationControllerId() {
    if (replicationControllerId == null) {
        try {//from  w  w w .  j a  v a2 s  .  c o m
            ObjectMapper mapper = KubernetesFactory.createObjectMapper();

            File file = new File(getBrokerTemplateLocation());
            URL url;
            if (file.exists()) {
                url = Paths.get(file.getAbsolutePath()).toUri().toURL();
            } else {
                ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
                url = classLoader.getResource(getBrokerTemplateLocation());
            }

            if (url != null) {
                ReplicationController replicationController = mapper.reader(ReplicationController.class)
                        .readValue(url);
                replicationControllerId = replicationController.getId();
                ReplicationController running = kubernetes.getReplicationController(replicationControllerId);
                if (running == null) {
                    kubernetes.createReplicationController(replicationController);
                    LOG.info("Created ReplicationController " + replicationControllerId);
                } else {
                    LOG.info("Found ReplicationController " + running.getId());
                    replicationControllerId = running.getId();
                }

            } else {
                LOG.error("Could not find location of Broker Template from " + getBrokerTemplateLocation());
            }

        } catch (Throwable e) {
            LOG.error("Failed to create a Broker", e);
        }
    }
    return replicationControllerId;
}

From source file:org.apache.hadoop.security.alias.JavaKeyStoreProvider.java

private JavaKeyStoreProvider(URI uri, Configuration conf) throws IOException {
    this.uri = uri;
    path = ProviderUtils.unnestUri(uri);
    fs = path.getFileSystem(conf);//from www  .j  a v a 2s  .  c o m
    // Get the password from the user's environment
    if (System.getenv().containsKey(CREDENTIAL_PASSWORD_NAME)) {
        password = System.getenv(CREDENTIAL_PASSWORD_NAME).toCharArray();
    }
    // if not in ENV get check for file
    if (password == null) {
        String pwFile = conf.get(KEYSTORE_PASSWORD_FILE_KEY);
        if (pwFile != null) {
            ClassLoader cl = Thread.currentThread().getContextClassLoader();
            URL pwdFile = cl.getResource(pwFile);
            if (pwdFile != null) {
                InputStream is = pwdFile.openStream();
                try {
                    password = IOUtils.toString(is).trim().toCharArray();
                } finally {
                    is.close();
                }
            }
        }
    }
    if (password == null) {
        password = KEYSTORE_PASSWORD_DEFAULT.toCharArray();
    }
    try {
        keyStore = KeyStore.getInstance(SCHEME_NAME);
        if (fs.exists(path)) {
            // save off permissions in case we need to
            // rewrite the keystore in flush()
            FileStatus s = fs.getFileStatus(path);
            permissions = s.getPermission();

            keyStore.load(fs.open(path), password);
        } else {
            permissions = new FsPermission("700");
            // required to create an empty keystore. *sigh*
            keyStore.load(null, password);
        }
    } catch (KeyStoreException e) {
        throw new IOException("Can't create keystore", e);
    } catch (NoSuchAlgorithmException e) {
        throw new IOException("Can't load keystore " + path, e);
    } catch (CertificateException e) {
        throw new IOException("Can't load keystore " + path, e);
    }
    ReadWriteLock lock = new ReentrantReadWriteLock(true);
    readLock = lock.readLock();
    writeLock = lock.writeLock();
}